The awk command in Linux

The awk command(stands for Aho, Weinberger, and Kernighan) is a great way to process and analyze a file of strings. In order for the files to be more informative, they have to be organized in the form of rows and columns. Then, you can use awk on these files to:

  • Scan the files, line by line.
  • Split each line into fields/columns.
  • Specify patterns and compare the lines of the file to those patterns
  • Perform various actions on the lines that match a given pattern

In this article, we will explain the basic usage of the awk command and how it can be used to split a file of strings.

Use Awk to print all lines of a file

$ awk '{print}’ filename.txt

Use awk to print only the lines that match a given pattern

$ awk '/pattern_to_be_matched/ {print}' filename.txt

For example, if you want to to print only the line(s) that contain “happy”, you can use the following command:

$ awk '/happy/ {print}' filename.txt

Use awk to split the file so that only specific fields/columns are printed

$ awk '{print $N,….}' filename.txt

The following example will show you how to print only the first column and second column in a file ( I am assuming we have a file, and words in a line will be split by space/tab)

$ awk '{print $1, $2}' filename.txt

Use awk to print only non-empty lines from a file

$ awk 'NF > 0' sample_file.txt

Obviously, you can use the following command to print the empty lines:

$ awk 'NF < 0' sample_file.txt

Use awk to count the total lines in a file

$ awk 'END { print NR }' sample_file.txt

This post gave you the basic use cases in the awk command. You can use man command to find out more useful from the awk command.
Thank you for reading!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s