The awk command allows you to browse files and launch the execution of certain actions. The foundations of this Linux command date back to 1977.
Linux awk command: what is it?¶
With its awk command, Linux has a scripting and programming language that allows evaluate and process files. This command already exists since 1977. Its name comes from its three developers: Alfred Aho, Peter Weinberger and Brian Kernighan. This tool is used via the command line or the SSH (Secure Shell) protocol. The awk command is used to search for certain patterns defined in files, similar to the Linux grep command. These files can then be modified automatically, under certain circumstances and according to certain parameters.
How does the awk command work?¶
The awk command combines conditions and statements. When you run this command in a file, it goes through it line by line. Each time, it checks if the defined condition is met. The corresponding statement executes if the condition is met for the row being evaluated. If no condition is defined, the statement executes on each new line. If no instruction is specified, only the standard instruction of the entry line is executed. In particular, you can use the Linux awk command to search your files for specific terms or patterns.
What does the awk command syntax look like?¶
The Linux awk command syntax is as follows:
$ awk [Options] " Condition {Instructions}" [Fichier de sortie]
shell
What are the Linux awk command options?¶
You have the choice between three options:
- -F [séparateur] : this option sets the separator for a file, with a space as the default.
- -f [nom du fichier] : this option determines the file in which the awk command is executed.
- -v: this option can be used to add a variable.
awk command: example¶
To better understand how to use the awk command, discover with us how it works thanks to a simple example. Here we will use a simple file, called example.txt. It contains a list of cities, countries and continents divided into different columns. It looks like the following:
Ville Pays Continent
Berlin Allemagne Europe
Paris France Europe
Hanoï Vietnam Asie
Abuja Nigeria Afrique
shell
To view the complete file, you can now use the following command:
$ awk "{print $0}" exemple.txt
shell
The stakes become more interesting if you only want to display certain columns. In this example, we have chosen the first and the third:
$ awk "{print $1, $3}" exemple.txt
shell
We then obtain the following result:
Berlin Europe
Paris Europe
Hanoï Asie
Abuja Afrique
shell