Wednesday, July 16, 2008

Merge previous line using sed


Input file:

$
cat file.txt
1 AA 2
2 BB 3
3 DD 4
5 CC 12
7 ZZ 12

Required output:
If I search for line with first field as "3" , th line with first field 3 should be merged with the previous line to it.
i.e

1 AA 2
2 BB 3 3 DD 4
5 CC 12
7 ZZ 12

Awk code:

$ awk 'NR==1{printf $0;next}
/^3\>/{printf " " $0;next}
{printf "\n" $0}
END{print ""}
' file.txt


or if you just want to print that affected line only:

$ awk '/^3\>/{print l,$0}{l=$0}' file.txt
2 BB 3 3 DD 4

No comments:

© Jadu Saikia www.UNIXCL.com