Awk
Igor Džikajev
What is awk command?
awk is a scripting language, and it is helpful when working in the command line. It's also a widely used command for text processing. When using awk, you are able to select data – one or more pieces of individual text – based on a pattern you provide.
For example, some of the operations you can do with awk are searching for a specific word or pattern in a piece of text given, or even select a certain line or a certain column in a file you provide.
The Basic Syntax of the awk command
In its simplest form, the awk command is followed by a set of single quotation marks and a set of curly braces, with the name of the file you want to search through mentioned last.
It looks something like this:
awk '{action}' your_file_name.txt
When you want to search for text that has a specific pattern or you're looking for a specific word in the text, the command would look something like this:
awk '/regex pattern/{action}' your_file_name.txt
With information.txt file looking like this:
fristName lastName age city ID Thomas Shelby 30 Rio 400 Omega Night 45 Ontario 600 Wood Tinker 54 Lisbon N/A Giorgos Georgiou 35 London 300 Timmy Turner 32 Berlin N/A
We are able to
- Print all the contents of the file using awk '{print $0}' information.txt
- Add incrementing number before each line using awk '{print NR,$0}' information.txt
- Print specific columns using awk '{print $1}' information.txt *number represents column* It is also possible to print out multiple by adding $n after $1 awk '{print $1, $4}' information.txt or $NF to print out last column
- Print specific lines of a column by adding head or tail command to existing command // awk '{print $1}' information.txt | head -1
- Use regex awk ' /io/{print $0}' information.txt this will print out lines containing "io"
- Use comparisson operators awk '$3 < 40 { print $0 }' information.txt this will only print out lines where 3rd column (age) is <40
This wraps up everything there is to say about awk.