Search code examples
regexperlregex-lookarounds

Regex : replace a phrase only if NOT preceded by a word


I'm trying to replace some phrase ("my term") in text files with perl command line. Those files are divided in section, like this :

section1
my term
nothing abc

section2
some text
my term
another text

section3
some text
my term

section4
some text
my term

Some sections may not exist. What I want to achieve is replace "my term" by "some other term", but only if it is in section1. I tried some lookahead and lookbehinds syntax, but wasn't able to find a working solution (https://regex101.com/r/mfqay6/1)

For example, if I delete section 1, the following code match, whereas I don't want it :

(?!section2).*(my term)

Any help there ?


Solution

  • A simple one liner:

    perl  -ane 's/my term/some other term/ if(/section1/ ... /section/);print' file.txt 
    

    Output:

    section1
    some other term
    nothing abc
    
    section2
    some text
    my term
    another text
    
    section3
    some text
    my term
    
    section4
    some text
    my term