
Linux Command Line
The AWK command is a powerful tool in the Linux command line for text processing. It is particularly useful for quickly manipulating and analyzing large sets of data in a structured format, such as CSV or tab-delimited files.
One of the most common use cases for AWK is to extract specific columns from a file. For example, consider a file called “data.txt” with the following contents:
John,23,New York Mary,28,Chicago Bob,35,Los Angeles
To extract the first column (the names) using AWK, the command would be:
awk -F "," '{print $1}' data.txt
This tells AWK to use a comma as the field separator (indicated by the -F flag) and to print the first field. The output would be:
John Mary Bob
Another useful feature of AWK is its ability to perform calculations on columns of data. For example, to calculate the average age in the above file, the command would be:
awk -F "," '{sum+=$2} END {print sum/NR}' data.txt
This command tells AWK to use a comma as the field separator, add the second field to the variable “sum”, and then after all lines have been read, divide the sum by the number of rows (NR). The output would be:
28
AWK also supports more complex operations, such as conditional statements and loops. For example, the following command will print the names of all people from New York:
awk -F "," '$3 == "New York" {print $1}' data.txt
This command tells AWK to use a comma as the field separator and to check if the third field is equal to “New York”, if true, it will print the first field. The output would be:
John
AWK is also a versatile tool for text processing and manipulation, it can perform many other tasks like counting the number of lines, counting the number of occurrences of a word, replacing a word, etc.
In conclusion, AWK is a powerful tool for text processing that can be used to quickly extract and manipulate data in a structured format. The examples above demonstrate some of the basic capabilities of the command, but with its many options, AWK can be used for a wide range of tasks.
See our list of 75 Linux commands you should know about.