Awk Command in Linux

The awk command is used for text processing in Linux. Although, the sed command is also used for text processing, but it has some limitations, so the awk command becomes a handy option for text processing. It provides powerful control to the data.

Features of AWK command

Various features of the Awk command are as follows:

  • It scans a file line by line.
  • It splits a file into multiple fields.
  • It compares the input text or a segment of a text file.
  • It performs various actions on a file like searching a specified text and more.
  • It formats the output lines.
  • It performs arithmetic and string operations.
  • It applies the conditions and loops on output.
  • It transforms the files and data on a specified structure.
  • It produces the format reports.

Awk is a utility used for data extraction. It is usually used to extract fields from a file or output.

Syntax :

awk '/search_pattern/ { action_to_take_on_matches; another_action; }' file_to_parse

The command to check the version of awk is:

awk --version

The awk '{print $1}' filename command lists the first field from a file.

linux-fundamental39

The awk command not only works on a file system, but it can also act on an output of a command. The command ls -l filename | awk '{print $1,$2}' shall obtain the first and second fields of ls -l output.

linux-fundamental40

The command ls -l filename | awk '{print $NF}' shall obtain the last field of ls -l output.

linux-fundamental41

The command awk '/search word/ {print}' filename shall search for a specific word in the file.

linux-fundamental42

The command which gives the list of columns separated by delimiter: from the passwd file :

            awk -F: '{print $1}' /etc/passwd

The command awk 'length($0) < 10' filename shall get lines that have less than ten bytes size.

linux-fundamental43

The command which shall get the field matching cutcommand in /home/saby in the output obtained from another command is.

                             ls -l | awk '{if ($9) == "cutcommand") print $0;}

The command which shall get the number of fields in the output obtained from ls -l is.

         ls -l | awk '{print NF}'
About Author :

Myself Debomita Bhattacharjee, an IT employee with 6+ years of experience in Software industry. My area of interest is Automation testing and Front End Development.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions