The awk
command is used to edit the command output or text files in a streaming way. The awk command provides a lot of features and commands to print content of the provided text. We can use the awk command in order to print range of columns.
Print Range of Columns
The print
command can be used to print specific olumns where the columns are specified using their index numbers like $1
, $2
, … . In the following example we use { print $2, $3, $4}
to print 2,3,4 columns.
$ cat names | awk '{ print $2, $3, $4, $5 }'
Alternatively we can also print range of columns for a command output.
$ ls -l | awk '{ print $2, $3, $4, $5 }'
Print Range of Columns with for Loop
As a powerful command the aws provides for loop to print range of columns.
$ awk '{for(i=1;i<=NF-1;i++) printf $i" "; print ""}' names.txt
Print Range of Columns Using NF Variable
We can use NF
variable to print range of columns. The NF variable is used to store number of fields or columns.
$ awk '{print $(NF-3)" "$NF}' names.txt
Print Range of Columns Using substr() and index() Methods
The awk command provides the substr()
and index()
methods in order to return substring and index numbers.
$ awk '{print substr($0,index($0,$3))}' names.txt
Print Range of Columns Using printf Methods
The printf
command can be used to print columns using the awk command.
$ awk '//{printf "%10s %10s %10s\n",$2,$4,$3 }' names.txt