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?
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
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.
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
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)