By using the awk command, you can look through files and carry out certain actions. The basis of this Linux command goes all the way back to 1977.

What is the Linux awk command?

Linux has a script and pro­gram­ming language you can use to evaluate and edit files. Called awk, it has its origins all the way back in 1977. The name is taken from the three de­velopers: Alfred Aho, Peter Wein­ber­ger and Brian Kernighan. You can easily use the tool via the command bar or SSH (Secure shell). Much like when you are using the Linux grep command you can use the awk command to search for certain patterns in files and then if other con­di­tions are met they can be edited.

How does the awk command work?

Awk uses a com­bin­a­tion of con­di­tions and in­struc­tions. By running the command it will go through the file line by line looking for certain con­di­tions. If it finds those con­di­tions in a line, it will carry out the in­struc­tion there. If there is no condition set, then the in­struc­tion will be carried out on every line. If you don’t enter an in­struc­tion, the standard in­struc­tion from the entry row is carried out. This means you can use Linux awk to search for certain terms or examples in files.

How does the awk syntax look?

The syntax for the Linux awk command looks as follows:

$ awk [Options] "Operation {Instructions}" [Target file]
shell

What options does the awk command have?

You have three options available to you:

  • -F [Separator]: You can use this option to set a separator between files. This is usually a single space.
  • -f [File name]: You can use this option to set in which file you want to run the awk command.
  • -v: Use this option to add a variable.

Examples of the awk command

To get a better un­der­stand­ing of how you can use ask, here are a few examples. In this case we are using a file called example.txt which includes a list of cities, countries and con­tin­ents in in­di­vidu­al columns. It looks as follows:

City Country Continent
Washington D.C USA America
Paris France Europe
Hanoi Vietnam Asia
Abuja Nigeria Africa
shell

If you want to output the entire file then you need to use the following command:

$ awk "{print $0}" example.txt
shell

However, if you just want to see in­di­vidu­al columns then you can use a separate command. In our case it’s the first and third columns:

$ awk "{print $1, $3}" example.txt
shell

This will return the following output:

Washington D.C America
Paris Europe
Hanoi Asia
Abuja Africa
Go to Main Menu