I'm having a problem with sed, when using its 's' (search and replace command) with its 'e' flag, as in
sed 's/.../.../e'
The problem is that the characters $
, (
, and )
in the standard input appear to confuse it.
I first ran into it here and have now boiled it down to this:
echo '$-' | sed 's/x//e' # works when pattern is NOT matched
$-
echo '$-' | sed 's/-//e' # fails when pattern is matched: gags on $
sh: $: command not found
echo '-' | sed 's/-//e' # works when $ isn't present
echo '-(' | sed 's/-//e' # Also fails when '(' or ')' are found
sh: -c: line 1: syntax error: unexpected end of file
echo '(' | sed 's/-//e' # But works with this
(
echo '$-' | sed 's/-/echo xx/e' # also fails
sh: xx: command not found
echo '$-' | sed 's/\(-\)/echo '\1'/e' # also fails
sh: 1: command not found
Here's what the GNU manual says:
3.3 The s Command
...
The s command can be followed by zero or more of the following flags:
...
e
This command allows one to pipe input from a shell command into pattern space. If a substitution was made, the command that is found in pattern space is executed and pattern space is replaced with its output. A trailing newline is suppressed; results are undefined if the command to be executed contains a NUL character. This is a GNU sed extension.
bash --version
GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)
sed --version
sed (GNU sed) 4.7
Packaged by Debian
What am I missing or doing wrong?
echo '$-' | sed 's/-//e'
.first, sed reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed
. Withecho '$-' | sed 's/-/echo xx/e'
the pattern space is notecho xx
. The pattern space is$-
at first, thens
does its job and the pattern space becomes$echo xx
.