elmama
​A selection of topics on IT and its application to finance. 
​Send me your comments, questions ​or suggestions by clicking
h​ere



Some useful awk scripts

I came across this useful awk command the other day. Suppose you need to find a pattern in a text file a, print the line out containing it but also print out the nth line after that too.

 

Here's one way.

 

First of all here in my input text file that I'm searching

 

AAAA BBBB CCCC DDDD

Line 2

Line 3

Line 4

Line 5

Line 6

Line 7

Line 8

 

Let's say I want to find the line containing BBBB, print it out and also print out the 3rd line after that e.g Line 4

 

e.g We want

 

AAAA BBBB CCCC DDDD

Line 4

 

The following comand will do it.

 

awk "/BBBB/{i=1;print}!i{next}{if(i++==4){print}}"   x.txt{cke_protected_1} 

 

 

You can extend this slightly by changing the  if(i++==4) line. Let's say you want ed the target string plus lines 3,4 5and 5 after it too.

 

e.g

AAAA BBBB CCCC DDDD

Line 3

Line 4

Line 5

 

This will do it

 

awk "/BBBB/{i=1;print}!i{next}{if(i++>=3 && i <= 6){print}}"   x.txt

 

Now what about the flip side of this. You want to print out one or more lines before a pattern match

 

awk "/Line 8/{for(i=1;i<=x;)print a[i++];print}{for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}" x=3 x.txt

 

 

The above will print out

 

Line 5

Line 6

Line 7

Line 8

 

i.e the pattern match (line 8) and the 3 lines immediately before it

​​