Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print lines above and below regex 1

Status
Not open for further replies.

cryptoadm

MIS
Nov 6, 2008
71
US
abc = 1234
def = nnnn
ghi = XXX
jkl = yes

abc = 2345
def = nnoo
ghi = ZZZ
jkl = yes

abc = 6789
def = uuuu
ghi = XXX
jkl = no

I have output similar to the above and I can use sed to print lines above a regex or lines below. But how do I print above and below if I match a regex which in this case is XXX?

Example:

1234
nnnn
XXX
yes

6789
uuuu
XXX
no

Thanks!
 
Try this:

Code:
awk '
        # strip off the beginning of each line and add to holding variable
        { sub(".*= *","");h=h $0 "\n" }
        # match found, print holding variable and subsequent line
        /XXX/ { printf h; getline; sub(".*= *",""); printf $0 "\n\n" }
        # blank line found, empty the holding variable for next record
        /^$/ { h="" }
' inputfile > outputfile


Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top