Skip to main content

Posts

Showing posts with the label awk

Print next line after a pattern

Just had a requirement to print the current line with pattern and next line. This seems to be pretty straight forward with AWK awk '/YOUR_STRING/{c=1;{print}next}c-->0'   <yourFile> if you put c=2, it will print the next two lines   Eg.  sampleData.txt containg.. EmployeeName ABC XYZ QPR LMN awk '/EmployeeName/{c=1;{print}next}c-->0'   sampleData.txt will print.. EmployeeName ABC if you don't want headers.. awk '/EmployeeName/{c=1;next}c-->0'   sampleData.txt  

Complex examples of AWK

AWK is very powerful and newer generations nawk and gawk do have better flexibility. They are widely used by fellow scripters due to its sheen power. Let's look into some complex examples of AWK variants. I would recommend using nawk format as its installed in most of the Unix systems (AIX, Linux, Ubuntu have nawk by default) Syntax for one line awk commands   awk:  awk -Fs                     '/search/ {action}' awkvar=$shellvar infile nawk: awk -Fs -v awkvar=$shellvar '/search/ {action}'                  infile gawk: awk -Fs -v awkvar=$shellvar '/search/ {action}'                  infile   BEGIN { }, { } and end { } An awk script can have three types of blocks. One of them must be there. a) The BEGIN{} block is processed before the file is checked. b) The {} block runs for every line of input c) The END{} block is processed after the final line of the input file.   awk ' BEGIN    { myvalue = 1000 } /debt/   { myvalue -= $2  } /want/   { myvalue += $4