Need you assistance on sed selective printing.

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Need you assistance on sed selective printing.

Sara
Hi Guru,
Need you assistance on sed selective printing.
My file contains the below
$cat new
:20A:XXX-XX
:20B:AXSASAAA
:21F:12345678-X
:22C:5555
:20A:XXX-X1
:20B:AXSASAAA1
:21F:12345678-X1
:22C:4444
:20A:XXX-X2
:20B:AXSASAAA2
:21F:12345678-X2
:22C:3333
:20A:XXX-X3
:20B:AXSASAAA3
:21F:12345678-X3
:22C:2222

Using below sed, I have printed the line immediately before/after the pattern but not that line.
sed –n –e  '/regexp/{g;1!p;};' –e h new (to print before line)
sed -n '/:21F:/{n;p;}' new (to print after line)

I want to print the 2 lines immediately before/after the pattern but not that line. I.e. if the search pattern is ‘:21F:’ then 2 lines before the line which matches the pattern ‘:21F:’
:20A:XXX-XX
:20B:AXSASAAA
:20A:XXX-X1
:20B:AXSASAAA1
:20A:XXX-X2
:20B:AXSASAAA2
:20A:XXX-X3
:20B:AXSASAAA3

Please advice how to achieve this using sed.

Regards,
Sara
Reply | Threaded
Open this post in threaded view
|

Re: Need you assistance on sed selective printing.

Guru
Administrator
Hi Sara
   
Lines after pattern:

$ sed -ne '/21F/{N;N;s/[^\n]*\n//;p;}' file
:22C:5555
:20A:XXX-X1
:22C:4444
:20A:XXX-X2
:22C:3333
:20A:XXX-X3


Lines before pattern:
$ sed -ne '/21F/{s/.*//;x;p;};H;{x;s/.*\n\(.*\n.*$\)/\1/;x;}' file
:20A:XXX-XX
:20B:AXSASAAA
:20A:XXX-X1
:20B:AXSASAAA1
:20A:XXX-X2
:20B:AXSASAAA2
:20A:XXX-X3
:20B:AXSASAAA3


For more explanation on the sed commands used, check this: http://www.theunixschool.com/2012/06/sed-25-examples-to-delete-line-or.html


Reply | Threaded
Open this post in threaded view
|

Re: Need you assistance on sed selective printing.

Sara
Thanks Guru.