AWK Command

What is AWK?

  • AWK is a powerful scripting language used to manipulate data and generate report.
  • AWK utiltiy scan a file line by line
  • Split each lines which is scanned into fields separated by delimiter.
  • Compares the scanned fields with the given pattern and matches it.
  • Perform operation on the output that is matched

Syntax of AWK

awk options 'selection _criteria {action }' input-file > output-file

We are going to perform search operation on the below text file demo.txt

cat demo.txt 
Tyson
Demo 332
Hello World
DemO
987 Democode
  • Display all the lines in the file demo.txt?
awk '{ print }' demo.txt
  • Display 1st column of every text in file demo.txt?
awk '{ print $1 }' demo.txt

$1 in the above command prints the first column and no delimiter is specified because by default the delimiter is space.You can specify the delimiter by using -F attribute just like in the example below where the delimiter is colon (:)

You can also concatenate two columns using . operator

  • Find every line in file demo.txt which contains the word demo in regex
awk '/Demo/ { print }' demo.txt
  • Find line in the file demo.txt which starts with a number
awk '/^[0-9]/ { print }' demo.txt
  • Find if the second column contains the number 332
awk ' { if ( $2 ~ /332/)  print } ' demo.txt

In the above example $2 stands for 2nd column and tilda symbol ~ stands for equals to.

  • Print line from 2 to 4 in demo.txt
awk 'NR==2,NR==4 {print} ' demo.txt
  • Perform Arithmetic operation using AWK
echo 22 7 | awk '{ print $1/$2 }'
echo 22 7 | awk '{ print $1*$2 }'
echo 22 7 | awk '{ print $1+$2 }'
echo 22 7 | awk '{ print $1-$2 }'

Reference / Learning Points :

https://hackr.io/tutorials/learn-awk

Leave a Comment