Sunday, January 14, 2007

Same task, different ways of doing


Here I am discussing some small operations with their alternative ways of doing.

A) Removing Blank Lines

$ cat test.out
this is line 1
this is line 2
some lines here


there are 2 blank lines above
this is last line

$ grep -v '^$' test.out
$ grep '.' test.out
$ sed '/^$/d' test.out
$ sed -n '/^$/!p' test.out
$ awk NF test.out
$ awk '/./' test.out

$ cat test1.out
this is line 1
this is line 2
some lines here
this is last line

B) Lines that doesn't contain a particular regexp
$ grep -v 'this' test1.out
$ awk '!/this/' test1.out
$ sed '/this/d' test1.out
$ sed -n '/this/!p' test1.out

will print
some lines here

Printing last Line
$ tail -1 test1.out
$ sed '$!d' test1.out
$ sed -n '$p' test1.out
$ awk 'END {print}' test1.out

will print
this is last line

C) Printing first line
$ head -1 test1.out
$ sed q test1.out
$ awk 'NR>1 {exit};1' test1.out

will print
this is line 1

D) Number of lines in a file
$ wc -l test1.out | cut -d " " -f1
$ sed -n '$=' test1.out
$ awk 'END {print NR}' test1.out

E) Printing first 2 lines
$ awk 'NR<3'>
$ head -2 test1.out
$ sed '1,2 p' test1.out

$ cat names.out
Lehe
Alex
Themo
Demo
Saik

F) Print the line immediately before a regex, but not the line containing the regex

$ awk '/Alex/ {print x};{x=$0}' names.out
$ sed -n '/Alex/{g;1!p;};h' names.out
$ S=`grep -n Alex names.out | awk -F : '{print $1}'`; S=`expr $S - 1`; sed -n "$S p" names.out

will print
Lehe

G) print the line immediately after a regexp, but not the line containing the regexp

$ sed -n '/Lehe/{n;p;}' names.out
$ awk '/Lehe/{getline;print}' names.out
$ S=`grep -n Lehe names.out | awk -F : '{print $1}'`; S=`expr $S + 1`; sed -n "$S p" names.out

will print
Alex

No comments:

© Jadu Saikia www.UNIXCL.com