So, the regular expression syntax depends on the version of sed you're using.
First off, according to the POSIX specification, basic regular expressions (BRE) do not support alternation. However, tools do not necessarily follow the specification and, in particular, different versions of sed have different behavior.
The examples below are all processing this file:
$ cat sed-re-test.txt
OtherElement "user.name"
OnlyReplaceMe "user.name"
ApplicationUser "user.name"
GNU sed
The GNU sed BRE variant supports alternation but the |
metacharacter (along with (
and )
) must be escaped with a \
. If you use -E
flag to enable Extended Regular Expressions (ERE), then the metacharacters must not be escaped.
$ sed --version
sed (GNU sed) 4.4
<...SNIP...>
GNU sed BRE variant (with escaped metacharacters): WORKS
$ cat sed-re-test.txt | sed '/\(OtherElement\|ApplicationUser\)/!s/"user.name"/"user.name@abc.com"/g'
OtherElement "user.name"
OnlyReplaceMe "user.name@abc.com"
ApplicationUser "user.name"
GNU sed ERE (with unescaped metacharacters): WORKS
$ cat sed-re-test.txt | sed -E '/(OtherElement|ApplicationUser)/!s/"user.name"/"user.name@abc.com"/g'
OtherElement "user.name"
OnlyReplaceMe "user.name@abc.com"
ApplicationUser "user.name"
BSD/MacOS sed
BSD sed does not support alternation in BRE mode. You must use -E
to enable alternation support.
No --version
flag, so identifying the OS will have to do:
$ uname -s
OpenBSD
BSD sed BRE (with escaped and unescaped metacharacters): DOES NOT WORK
$ cat sed-re-test.txt | sed '/\(OtherElement\|ApplicationUser\)/! s/"user.name"/"user.name@abc.com"/'
OtherElement "user.name@abc.com"
OnlyReplaceMe "user.name@abc.com"
ApplicationUser "user.name@abc.com"
$ cat sed-re-test.txt | sed '/(OtherElement|ApplicationUser)/! s/"user.name"/"user.name@abc.com"/'
OtherElement "user.name@abc.com"
OnlyReplaceMe "user.name@abc.com"
ApplicationUser "user.name@abc.com"
BSD sed ERE (with unescaped metacharacters): WORKS
$ cat sed-re-test.txt | sed -E '/(OtherElement|ApplicationUser)/! s/"user.name"/"user.name@abc.com"/'
OtherElement "user.name"
OnlyReplaceMe "user.name@abc.com"
ApplicationUser "user.name"