AWK script is suitable for pattern search and processing which runs to search one or more files to identify matching patterns and if the said patterns perform specific tasks. It allows you to write mini scripts in the form of terminal commands with which you can easily manipulate the files in Linux.
Here at LinuxAPT , we shall look into the most significant features of the AWK command in Linux, and then we will head on to a few examples that make use of this command.
If you have the test file (testfile.txt) with contents below:
1 Birmingham 0121
2 Edinburgh 0131
3 Glasgow 0141
4 Liverpool 0151
5 Leeds 0113
In this case, we wish to print a single column of the text file using the below command:
$ awk '{print $2}' testfile.txt
Birmingham
Edinburgh
Glasgow
Liverpool
Leeds
This command will print the second column of the test file, i.e., the names of the cities of the UK on the terminal.
Now, we will use the AWK command for printing multiple columns of the file at the same time on the terminal with the AWK command:
$ awk '{print $2, $3}' testfile.txt
This command will print the second and third columns of the test file, i.e., the names of the cities of the UK and their respective area codes on the terminal. However, if you will skip the comma between the column numbers in the above-mentioned command, then these columns will be printed without any space in between.
Birmingham 0121
Edinburgh 0131
Glasgow 0141
Liverpool 0151
Leeds 0113
In this case, we want to pair up the AWK command with the logical operators in Linux. We want to define different conditions to get the desired output with the below command:
$ awk '$1>3 && $3>0000 {print $2}' testfile.txt
This command will only print those entries from the second column of our file where the value of the first column will be greater than "3", and that of the third column will be greater than "0000". In the same manner, you can also use the "||" operator with the AWK command to define any condition of your choice.
Liverpool
Leeds
Now, we want to use the AWK command for printing the file-related information on the terminal, such as the name of the file, the total number of rows and columns, etc. For that, we have used the AWK command:
$ awk 'END{print “The name of the file is “, FILENAME, “It has “, NF, “columns and “, NR, “rows”}' testfile.txt
This command will print the name of the file and the total number of rows and columns that it contains on the terminal. "NF" and "NR" are the built-in variables of the AWK command that refer to the total number of fields and the total numbers of records, respectively, present in a file. Again, if you will skip the commas in this command, then your output will look extremely messy as it will be printed without any spaces on the terminal.
This article covers the usage of the AWK command in Linux. In fact, AWK can use to manipulate text in documents or perform specific functions.
It is given below:
$ awk options 'selection _criteria {action }' input-file > output-file