Friday, 3 July 2020

Learn awk by examples




AWK is a pattern-directed scanning and manipulating language, designed expecially for text processing.
It scans each input file for lines that match any of a set of patterns specified literally in prog or in one or more files specified as -f file. With each pattern there can be an associated action that will be performed when a line of a file matches the pattern.

A program basing on AWK is made of a list of rules that specify a pattern and the relative action to execute if the pattern is satisfied:

  pattern { action }


Example usages.

Suppose you have this file.txt:
Red     Blue    1
Orange  Pink    2
Yellow  Black   3
Green   White   4
Red     Purple  5


  • Print the lines from file.txt that contains the word "Blue"
$ awk '/Blue/ { print }' file.txt
Red     Blue    1 
 

  • Print the whole file:
$ awk '{print $0}' file.txt
Red     Blue    1
Orange  Pink    2
Yellow  Black   3
Green   White   4
Red     Purple  5 
 

  • Print the first column of the file:
$ awk '{print $1}' file.txt
Red
Orange
Yellow
Green
Red 
 

  • Print the second column of the file:
$ awk '{print $2}' file.txt
Blue
Pink
Black
White
Purple


  • Preprocessing: add an header to your output:
$ awk 'BEGIN {print "Second column:"} {print $2}' file.txt
Second column:
Blue
Pink
Black
White
Purple 
 

  • Postprocessing: add a footer to your output:
$ awk '{print $2} END {print "End of file!"}' file.txt
Blue
Pink
Black
White
Purple
End of file! 


  • Substitution: change the field separator (FS) with an output field separator (OFS) in file:
$ awk 'BEGIN{FS=" "; OFS="-"} {print $1,$2,$3}' file.txt
Red-Blue-1
Orange-Pink-2
Yellow-Black-3
Green-White-4
Red-Purple-5 
 
 




No comments:

Post a Comment