1

How can I use awk to modify lines that match a certain pattern, but only if the NEXT line does not match another pattern?

For example take this fragment:

....
pattern1 100 200 300
pattern1 300 400 400
pattern2 300 900 700
pattern1 200 500 900
...

I would like to modify all lines containing pattern1, except for the second one which is followed by a line containing pattern2.

This is similar to this question, but just the other way around.

  • 2
    Modify how? Depending on the constraints, you could save the previous line and modify it in the next line's iteration – muru Jan 11 '17 at 12:08
  • I need to replace a string – Grodriguez Jan 11 '17 at 12:19
1

try something like

/pattern2/ { print intact ; print $0 ; next ;}
! /pattern2/  { print new ;}
{ intact=$0 ; $1="p1" ; new=$0 ; }

there is an extra empty line

result is

p1 100 200 300
pattern1 300 400 400
pattern2 300 900 700
p1 300 400 400
0

This does what I needed:

/pattern1/ {
    if (candidate) {
        print "modify:", candidate
    }
    candidate=$0
    next
}

/pattern2/ {
    if (candidate) {
        print candidate
        candidate=0
    }
}

{
    if (candidate) {
        print "modify:", candidate
        candidate=0
    }
    print $0
}
0
sed -e '
   /pattern1/!b
   $q; N
   /\npattern2/!s/^/MODIFIED:/
   P;D
' yourfile

perl -0777pe 's/(?=pattern1.*$)(?!pattern2)/MODIFIED:/gm' yourfile
  • I am asking specifically about awk. – Grodriguez Mar 13 '17 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.