Linux/UNIX Awk Command Tutorial with Examples

  
AWK Stands for ‘Aho, Weinberger, and Kernighan‘
Awk is a scripting language which is used for processing or analyzing text files. Or we can say that awk is mainly used for grouping of data based on either a column or field , or on a set of columns. Mainly it’s used for reporting data in a usefull manner. It also employs Begin and End Blocks to process the data.

Syntax of awk :

# awk ‘pattern {action}’ input-file > output-file

Lets take a input file with the following data

$ cat awk_fileName,Marks,Max MarksRam,200,1000Shyam,500,1000Ghyansham,1000Abharam,800,1000Hari,600,1000Ram,400,1000Example:1 Print all the lines from a file.

By default, awk prints all lines of a file , so to print every line of above created file use below command :

linuxtechi@mail:~$ awk ‘{print;}’ awk_fileName,Marks,Max MarksRam,200,1000Shyam,500,1000Ghyansham,1000Abharam,800,1000Hari,600,1000Ram,400,1000

Example:2 Print only Specific field like 2nd & 3rd.

linuxtechi@mail:~$ awk -F “,” ‘{print $2, $3;}’ awk_fileMarks Max Marks200 1000500 10001000800 1000600 1000400 1000

In the above command we have used the option -F “,” which specifies that comma (,) is the field separator in the fileExample:3 Print the lines which matches the pattern

I want to print the lines which contains the word “Hari & Ram”

linuxtechi@mail:~$ awk ‘/Hari

Copyright © Windows knowledge All Rights Reserved