Friday, September 14, 2018

AWK Command - In an Easy way




Awk stands for Aho Weinberger and Kernighan. Awk is a scripting language to process and analyze files.
Some of the features of Awk are given below :
  • Awk actually work on data files.
  • Awk can generate formatted output.
  • Awk support different regular expressions.
  • Awk allows different features of traditional programming language like conditions, operators, loop , functions and so on.
Syntax of Awk command
  1. awk 'program' input_file
The simplest program is the sequence of actions. Each action has either pattern or no pattern. Each action is enclosed with braces. We explain with a typical file named input.txt that contains name , age and height like this :
  1. Mehedi 01 WDE 25000
  2. Arafat 02 WDE 27000
  3. Baki 03 SDE 30000
  4. Mahbub 04 ADE 29000
  5. Nazmul 05 SDE 24000
If action has pattern , then matches that pattern with files line by line until end of file and print the matches lines. Example :
  1. awk '$4>=25000 {print $1, $2 }' in.txt
Output are given below
  1. Mehedi 01
  2. Arafat 02
  3. Baki 03
  4. Mahbub 04
Otherwise, action is performed for all lines of input file.
  1. awk '{print $1, $2 }' in.txt
Output are given below :
  1. Mehedi 01
  2. Arafat 02
  3. Baki 03
  4. Mahbub 04
  5. Nazmul 05
We can also write program that has only pattern and action is missing. For these programs the matched line is printed. But it is not a good practice to write only pattern without action.
  1. awk '/WDE/' in.txt
Output :
  1. Mehedi 01 WDE 25000
  2. Arafat 02 WDE 27000
Some points about printing :
  • At the time of printing the all field of input lines we just write print.
  1. awk '{print }' in.txt
  • Otherwise we write print and particular column number with dollar sign like $1. For more column we obviously use comma as a separator.
  1. awk '{print $1, $2 }' in.txt

No comments:

Post a Comment

AWK Command - In an Easy way

Awk stands for Aho Weinberger and Kernighan. Awk is a scripting language to process and analyze files. Some of the features of Awk ...