Thursday, May 22, 2008

Print current,next,previous line using awk,sed - BASH


Print current line,next line,previous line using awk,sed - BASH

The sample file:

$ cat myfile.txt
AA SDF
BB DERT
CC DERA
DD TYU
EE ASDF
FF DERT


A) Print the line where pattern is found,print next line too using sed,awk,grep


i.e.
in the above file, if I search "^DD", it should print the following:

DD TYU
EE ASDF



$ awk '/^DD/{f=1;print;next}f{print;exit}' myfile.txt


One more using awk:

$ awk '
/^DD/{
print
getline
print
}' myfile.txt



$ sed -n '/^DD/{p;n;p;}' myfile.txt


$ grep -A1 "^DD" myfile.txt


B) print the line immediately after the pattern, not the line containing the pattern


i.e.

Output should be:

EE ASDF



$ awk '/^DD/{f=1;next}f{print;exit}' myfile.txt



$ awk '
/^DD/{
getline
print
}' myfile.txt



$ sed -n '/^DD/{n;p;}' myfile.txt


C) Print the line where pattern is found,print previous line too using sed,awk,grep


i.e.
in the above file, if I search "^DD", it should print the following:

CC DERA
DD TYU



$ awk '/^DD/{print x;print};{x=$0}' myfile.txt



$ grep -B1 "^DD" myfile.txt


D) print the line immediately before the pattern, not the line containing the pattern


i.e. If I search "^DD", output would be:

CC DERA



$ awk '/^DD/{print x};{x=$0}' myfile.txt

$ sed -n '/^DD/{g;1!p;};h' myfile.txt


Discussion: Use grep to print the current line (where pattern is found),its previous line, next line


$ cat myfile.txt
AA SDF
BB DERT
CC DERA
DD TYU
EE ASDF
FF DERT



$ grep -A1 -B1 "^DD" myfile.txt
CC DERA
DD TYU
EE ASDF


We can use for printing 2 lines before and 1 line after the line where pattern is found

$ grep -A1 -B2 "^DD" myfile.txt
BB DERT
CC DERA
DD TYU
EE ASDF


Similarly, printing 2 lines after and 1 line before the line where pattern is found

$ grep -A2 -B1 "^DD" myfile.txt
CC DERA
DD TYU
EE ASDF
FF DERT

2 comments:

vith said...

Thanks, that's just what I needed.

Jadu Saikia said...

@Vith, thanks :-)

© Jadu Saikia www.UNIXCL.com