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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

find pattern, delete line with pattern and previous line and next line 3

Status
Not open for further replies.

ng1

Technical User
Aug 22, 2007
39
0
0
US
I have a file that will sometimes contain a pattern. The pattern is this:


FRM CHK 000000

I want to find any lines with this pattern, delete those lines, and also delete the line above and the line below.
 
What have you tried so far and where in your code are you stuck ?

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
awk '/FRM CHK 000000/ { print last; print; x = 1; next }
x == 1 { print; x = 0 }
{ last = $0 }
' filename

Somebody gave me this. It prints out the lines I am trying to delete. I need to change their code so it deletes those lines instead of printing them.
 
sed '/FRM CHK 000000/{n;d;}’ filename

I have tried this. It gets rid of the line after my pattern. I still need to get rid of the line before my pattern and the line with my pattern.
 
Code:
awk '
/FRM CHK 000000/{x="";getline;next}
{if(x)print x;x=$0}
END{if(x)print x}
' filename

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Works great phv! Thank you.
 
Can someone explain how this works. I understand that you're replacing $0 with "" but how does getline replace the lines before and after the match?
 
No, it's not exactly replacing $0 with "". It's delaying the printing of each line until it reaches the following one, so that it can avoid printing the previous line when the pattern is found:

Code:
awk '
    # pattern found, empty saved line, read an extra line
    # so it is skipped
    /FRM CHK 000000/{x="";getline;next}
    # if a line has been previously saved, print it and save
    # the current one
    {if(x)print x;x=$0}
    # end of input, print the last saved line
    END{if(x)print x}
' filename

One (possibly undesirable) side effect of this method is that blank lines will not be printed. No problem if there are no blank lines in the input!

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top