awk is a command-line utility in Linux and Unix-like systems like FreeBSD that is used for text processing. It is particularly useful for working with structured text files, such as CSV or tab-separated files. awk reads input files, line by line, and performs actions based on the contents of each line. It can also perform actions based on the overall structure of the input file.
The basic syntax for awk is:
awk 'pattern { action }' inputfile
Where pattern is a regular expression that defines a condition for a line to be matched, and action is the command to be executed when a line matches the pattern.
Examples:
Print the second field of each line that contains the word “main”:
awk '/main/ { print $2 }' inputfile
Sum all the number in the second column of a file
awk '{ sum += $2 } END { print sum }' inputfile
Print the line number and the current line content
awk '{ print NR, $0 }' inputfile
Print the current line number and the total number of lines in the file
awk 'END { print NR }' inputfile
These are just a few examples of what awk can do. It has many more capabilities, including the ability to use variables, perform arithmetic and string operations, and even call external commands.