The awk
is a powerful Linux command line tool, that can process the input data as columns.
In the following note i will show how to print columns by numbers – first, second, last, multiple columns etc.
I will show how to change the default field separator in awk
.
At the end of this article i will also show how to print or exclude specific columns or even ranges of columns using awk
.
Cool Tip: Print lines of a file between two matching patterns using awk
or sed
! Read more →
AWK: Print Columns by Number
Print the all columns:
$ awk '{print $0}' FILE
Print the first column:
$ awk '{print $1}' FILE
Print the second column:
$ awk '{print $2}' FILE
Print the last column:
$ awk '{print $NF}' FILE
Print multiple columns (the first and the third columns):
$ awk '{print $1 $3}' FILE
Cool Tip: Add character to the beginning or to the end of each line of a file using awk
or sed
! Read more →
AWK: Change Field Separator
The field separator can be either a single character or a regular expression.
It controls the way awk
splits an input record into the fields.
By default, awk
uses both space
and tab
characters as the field separator.
You can tell awk
how fields are separated using the -F
option on the command line.
Use ,
(comma) as a field separator and print the first field:
$ awk -F "," '{print $1}' FILE
Use :
(colon) as a field separator and print the second field:
$ awk -F ":" '{print $2}' FILE
AWK: Exclude Columns
Print all the other columns but not the third one:
$ awk '{$3=""; print $0}' FILE
Print all the other columns but not the first and the second ones:
$ awk '{$1=$2=""; print $0}' FILE
Cool Tip: Remove blank lines from a file using grep
, tr
, sed
or awk
! Read more →
AWK: Print or Exclude a Range of Columns
Print a range of columns from the first till the fourth:
$ awk -v f=2 -v t=4 '{for(i=f;i<=t;i++) printf("%s%s",$i,(i==t)?"\n":OFS)}' FILE
Exclude a column range from the second till the fourth and print the rest:
$ awk -v f=2 -v t=4 '{for(i=1;i<=NF;i++)if(i>=f&&i<=t)continue;else printf("%s%s",$i,(i!=NF)?OFS:ORS)}' FILE
Very helpful, but how do you only print part of a line, for instance the last portion of a line followed by a “=”
The ‘=’ sign would be the delimiter and $NF is the last column.
Hi, how hould I print a column with spaces in it? If I use $1, it’d only print the first word only.
$0
You can insert spaces in your print statement like so:
$ awk ‘{print $1 ” ” $3 ” ” $5}’ FILE