awk command in Linux with examples

Hello, everyone In this Article we are going to learn how we can use the awk command in Linux with examples in a very simple and easy step-by-step approach.

awk

awk command

The drawback of cut command is that we cannot determine of the spaces between the fields

For Example when we Execute df -Th command we can see that there is unequal spaces between the fields

Screenshot 13

To deal with this situation we can use the awk command in order to display the values for the fields

In the awk command, we can use the $ symbol with the number to display the field for example If we want to display the field 1 then we can write $1 and soo on

To display the first field then we can execute below command

# df -Th | awk '{print $1}'
Screenshot 14

How to display specific fields

To display the first and fifth field then we can execute below command

# df -Th | awk '{print $1,$5}'
Screenshot 15

How to display the fields with alignment

To display the first and fifth field with the perfect alignment then we can add column command with ( -t ) option in awk command

# df-Th | awk '{print $1,$5}' | column -t
Screenshot 16

How to display the specific field

To display only xvda2 value then we can execute grep command with awk command

df -Th | grep xvda2 | awk '{print $5}'
Screenshot 17

we do not need % here – Then we can add ( -F ) Option in the awk command with the delimiter name that we don’t need

# df -Th | grep sda1 | awk '{print $5}' | awk -F'%' '{print $1}'
Screenshot 18

Now we only want to display the IP address

Screenshot 19

How to get specific field

To display only IP address value then we can execute grep command with ifconfig command and awk command

# ifconfig | grep -w inet | awk '{print $2}'
Screenshot 20

To display only value of 1st Ip then we can execute head command with awk command

# ifconfig | grep -w inet (only inet) | awk '{print $2}' | head -1
Screenshot 21

OFS (Outpour field separator) If we want to put anything between the fields then we can use OFS

Here we are putting :: delimiter between the fields

# ifocnfig | grep -w inet | awk '{print $2,$4}' OFS='::'
Screenshot 22

Here we are putting ( = ) delimiter between the fields

# tail -5 /etc/passwd | awk -F':' '{print $1,$6}' OFS='='
Screenshot 24

Conclusion

If you want to learn Linux in the most simple language then please click on this link.

If you want to see the man page of awk command online then click on this link

This is the complete knowledge of how we can use the awk command in the Linux kernel if you have any doubts please feel free to comment below. Please don’t forget to join our email subscription to get the latest updates on DevOps Articles.

Leave a Comment