AWK is a scripting language that analyzes text fields. It is widely used for processing data files containing lines and columns. AWK was first introduced in the 1970s. It has given the name based on the surnames of its developers: Alfred Aho, Peter Weinberger, and Brian Kernighan.
The basic format of AWK command is awk ‘pattern {action}’ input-file > output-file. Here actually, if the pattern is present in a line of the input file, awk will apply the action to the line and will write the resulting line to the output file.
Also Read: What is the Purpose of the Command Interpreter?
Use the Awk Command on Linux
The awk command is present by default in modern Linux systems. So, no need to install it. Here we have discussed some points on how to use awk command on Linux. So, here we go:
1. Print Specific Columns
To print a specific column one should use the command. For example, if you want to print 2nd and 3rd, use the following command:
$ awk '{print $2 "\t" $3}' file.txt
In any case, you want to print all the lines and columns in a file simply use the following command:
$ awk '{ print $0}' file.txt
2. Print Lines with Specific Pattern
$ awk '/variable_to_be_matched/ {print $0}' file.txt
One can use the above syntax for printing lines with a specific pattern. For example, if you want to print lines having the letter ‘o’ you have to add simply add ‘o’ in place of “variable to be matched”.
$ awk '/o/ {print $0}' file.txt
Also Read: How to Install Google Chrome Browser on Linux (Ubuntu)
3. Print Columns with Specific Pattern
$ awk ' /a/ {print $3 "\t" $4}' file.txt
This command will print 3rd and 4th columns that have the ‘a’ letter.
4. Built-in variables
For a better analysis of data, awk comes with several variables. Here, we described only a few of them.
NR: NR commands keep the current counts of the number of input records. To count the number of the input file, one can use the command:
$ awk ‘{print NR, $0}’ file.txt
NF: The NF variable keeps the count of fields for each record.
$ awk ‘{print NF, $0}’ file.txt
This command prints the last column of the table. One can also print the second last column of the table by using the command
$ awk ‘{print $2, $(NF -1) }’ file.txt
ORS: ORS stands for output record separator. It separates every line of the input file desirably.
$ awk ‘ BEGIN {ORS = “:” } {print $0}’ file.txt
OFS: OFS stands for output field separator. It separates every field in a desired output format.
$ awk ‘ BEGIN {OFS = “==” } {print $1, $2}’ file.txt
5. Arithmetic Operations
If the table contains numbers, the awk command can be used to perform arithmetic operations.
$ awk ‘{print $1 + $3 }’ file.txt
6. Saving Output
To save the output results, one can use the redirection operator “>”. Moreover, you can verify the result using the cat command.
$ cat output.txt
Awk command in Linux helps the programmer to write a useful program. Here we have discussed only a few commands. Hope you have liked the article and found it useful.