View and change certain fields of data using the AWK command in Linux

Home > Search > Linux commands
  by

The awk command is used to only display certain fields of output. In this context, a field is a string of data, delimited by whitespace. For example, the df -h command has fields of data delimited by whitespace.

 

Piping the output to awk '{print}' produces the same exact output.

[root@server1 ~]# df -h | awk '{print}'
Filesystem     Size    Used    Avail    Use%    Mounted on
/dev/md127     1.8T    1.1T     604G     65%    /
/dev/sda1      488M    100M     354M     22%    /boot

 

$1 will only print field 1.

[root@server1 ~]# df -h | awk '{print $1}'
Filesystem
/dev/md127
/dev/sda1

 

$5 will only print print 5.

[root@server1 ~]# df -h | awk '{print $5}'
Size
65%
22%

 

Let's add some custom text.

[root@server1 ~]# df -h | awk '{print $5, "of", $1, "used"}'
Filesystem is mounted on Mounted on
%65 of /dev/md127 used
22% of /dev/sda1 used

 


Specify delimiter

By default, whitespace separates fields. The /etc/passwd file is delimited by a colon.

user1:x:1001:1001::/home/user1:
user2:x:1002:1002::/home/user2:
user3:x:1003:1003::/home/user3:

 

The -F option can be used to specify a delimiter. For example, colon can be specified as the delimiter.

[root@server1 ~]# cat /etc/passwd | awk -F':' '{print $1}'
user1
user2
user3

 


Do not print certain lines

NR!=n can be used to not print certain lines. In this context, n is an integer, such as 1 or 2 or 3. As an example, NR!=1 will not print line 1.

~]# df -h | awk 'NR!=1{print $5, "of", $1, "used"}'
%65 of /dev/md127 used
22% of /dev/sda1 used

 


Only print certain lines

NR==n can be used to only print certain lines. In this example, only line 2 is printed.

~]# df -h | awk 'NR==2{print}'
/dev/md127     1.8T    1.1T     604G     65%    /

 

A range of lines can be specified. In this example, lines 1 through 3 are printed.

~]# df -h | awk 'NR==1,NR==3{print}'
Filesystem     Size    Used    Avail    Use%    Mounted on
/dev/md127     1.8T    1.1T     604G     65%    /
/dev/sda1      488M    100M     354M     22%    /boot

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments