Reputation: 177
I am trying to delete all lines with a specific pattern (PATTERN 2) only when the previous line has another specific pattern (PATTERN 1).
The code looks like this:
PATTERN 1
PATTERN 2 <- This line should be deleted
NNN
PATTERN 2
PATTERN 1
PATTERN 2 <- This line should be deleted
blabla
PATTERN 1
blabla
PATTERN 2
PATTERN 1
PATTERN 2 <- This line should be deleted
PATTERN 2 should be deleted ONLY when the previous line is PATTERN 1
However, I don't know to apply both requirements to a single AWK or SED.
How can this be done with AWK? Thank you in advance,
Upvotes: 2
Views: 166
Reputation: 163207
Another variation could be checking if the current line matches PATTERN 2
and the last line matches PATTERN 1
.
If that is the case, print the current line, else move to the next line without printing it.
awk '{if(/PATTERN 2/&&last~/PATTERN 1/){last=$0;next}last=$0}1' file
See an awk demo.
In a more readable format:
awk '
{
if (/PATTERN 2/ && last ~ /PATTERN 1/) { # If both patterns match
last = $0 # Save the last line, but don't print
next # Go on to the next record
}
last = $0 # Save the last line
}1 # Print the line
' file
Upvotes: 1
Reputation: 203189
Assuming by "PATTERN" you mean "partial regexp match" since that's what you use in the sed scripts in your question:
$ awk '!(/PATTERN 2/ && prev~/PATTERN 1/); {prev=$0}' file
PATTERN 1
NNN
PATTERN 2
PATTERN 1
blabla
PATTERN 1
blabla
PATTERN 2
PATTERN 1
Upvotes: 2
Reputation: 133428
With your shown samples/attempts, please try following awk
code.
awk '/PATTERN 1/{found=1;print;next} found && /PATTERN 2/{found="";next} 1' Input_file
Explanation: Adding detailed explanation for above.
awk ' ##Starting awk program from here.
/PATTERN 1/{ ##Checking if line contains PATTERN 1 then do following.
found=1 ##Setting found to 1 here.
print ##printing current line here.
next ##next will skip all further statements from here.
}
found && /PATTERN 2/{ ##Checking condition if found is NOT NULL AND PATTERN 2 is found.
found="" ##Nullifying found here.
next ##next will skip all further statements from here.
}
1 ##printing current line here.
' Input_file ##Mentioning Input_file name here.
Upvotes: 1
Reputation:
Mac_3.2.57$cat input | awk '{if(lastline!="PATTERN 1"||$0!="PATTERN 2"){print}};{lastline=$0}'
PATTERN 1
NNN
PATTERN 2
PATTERN 1
blabla
PATTERN 1
blabla
PATTERN 2
PATTERN 1
Mac_3.2.57$cat input
PATTERN 1
PATTERN 2
NNN
PATTERN 2
PATTERN 1
PATTERN 2
blabla
PATTERN 1
blabla
PATTERN 2
PATTERN 1
PATTERN 2
Mac_3.2.57$
Upvotes: 1