Sed regex and substring negation

前端 未结 4 358
耶瑟儿~
耶瑟儿~ 2020-12-13 13:29

What is the correct syntax for finding a substring (a string which is preceded and followed by specific strings) which does not match a specific pattern?

相关标签:
4条回答
  • 2020-12-13 13:57

    This topic may be old, but for the sake of completeness, what about the negation operator ! :

    Make all unhappy become VERY HAPPY :

    echo -e 'happy\nhappy\nunhappy\nhappy' | sed '/^happy/! s/.*/VERY HAPPY/'
    

    Found this here : How to globally replace strings in lines NOT starting with a certain pattern

    0 讨论(0)
  • 2020-12-13 14:07

    There is no general negation operator in sed, IIRC because compilation of regexes with negation to DFAs takes exponential time. You can work around this with

    '/BEGIN_FOO_END/b; s/BEGIN_\(.*\)_END/(\1)/g'
    

    where /BEGIN_FOO_END/b means: if we find BEGIN_FOO_END, then branch (jump) to the end of the sed script.

    0 讨论(0)
  • 2020-12-13 14:20

    This might work for you:

    sed 'h;s/BEGIN_\(.*\)_END/(\1)/;/^(FOO)$/g' file
    

    This only works if there is only one string per line.

    For multiple strings per line:

    sed 's/BEGIN_\([^F][^_]*\|F[^O][^_]*\|FO[^O][^_]*\|FOO[^_]\+\)_END/\(\1\)/g' file
    

    Or the more easily understood:

    sed 's/\(BEGIN_\)FOO\(_END\)/\1\n\2/g;s/BEGIN_\([^\n_]*\)_END/(\1\)/g;s/\n/FOO/g' file
    
    0 讨论(0)
  • 2020-12-13 14:21

    I don't know of a pretty way, but you could always do this:

    $ cat file
    BEGIN_FOO_END
    BEGIN_FrOO_END
    BEGIN_rFOO_END
    $ sed '/BEGIN_FOO_END/ !{s/BEGIN_\([^_]*\)_END/(\1)/}' file 
    BEGIN_FOO_END
    (FrOO)
    (rFOO)
    
    0 讨论(0)
提交回复
热议问题