awk Command in Linux: Process, Filter, and Edit Text Files
The awk command in Linux is a powerful tool that allows you to process texts and make changes to files. It can interpret small scripts to process a file or text.
There are other variants of AWK, such as: BWK, GAWK and MAWK, which are implementations from different developers with some improvements.
The awk command can receive commands directly as parameters, or through a file, using the "-f" option followed by the name of the file containing the commands.
Example:
Given a file with space-separated text, the "print" command will display something on the screen. The variables $0, $1, $2, $3 and $4 can print the entire content ($0), or each column of the text:
To print the entire file content:
$ awk '{print $0}' arquivo Leia Organa General ResistênciaLuke Skywalker Jedi ResistênciaDarth Vader Sith ImpérioObi-Wan Kenobi Jedi Resistência
To print only the first column:
$ awk '{print $1}' arquivo LeiaLukeDarthObi-Wan
To print the second column:
$ awk '{print $2}' arquivo OrganaSkywalkerVaderKenobi
It is also possible to play around with the text:
$ awk '{print $1 " " $2 " é um " $3 " da "$4}' arquivo Leia Organa é um General da ResistênciaLuke Skywalker é um Jedi da ResistênciaDarth Vader é um Sith da ImpérioObi-Wan Kenobi é um Jedi da Resistência
To list only the user logins in the /etc/passwd file, you can use the "-F" option, indicating the delimiter:
$ awk -F':' '{ print $1 }' /etc/passwdrootbindaemonadm
Awk can also be used to transform a text file or CSV into SQL commands:
$ awk '{print "insert into usuario (nome,sobrenome,cargo,departamento) values (\"" $1 "\",\"" $2 "\",\"" $3 "\",\"" $4 "\");" }' arquivoinsert into usuario (nome,sobrenome,cargo,departamento) values ("Leia","Organa","General","Resistência");insert into usuario (nome,sobrenome,cargo,departamento) values ("Luke","Skywalker","Jedi","Resistência");insert into usuario (nome,sobrenome,cargo,departamento) values ("Darth","Vader","Sith","Império");insert into usuario (nome,sobrenome,cargo,departamento) values ("Obi-Wan","Kenobi","Jedi","Resistência");
The only care to take is to reference the quotes that make up the SQL command with the backslash "\", so that they are interpreted as text and not as quotes.
Awk accepts the directives if, for and while like in the C language, as well as mathematical operators and many other things. In short, it is a complete tool for transforming files.
Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.
Liked it? Share
That was just one piece. The course teaches the whole path — from your first command to exam day.