0

Here's what I'm trying to replicate:

$ cat << EOF | { var=$(grep 'foo=');\
 if (( $? == 0 )); then echo "$var"\
| sed -E 's/foo=(.+)/\1/'; else exit 1; fi; }
foo
foo=bar
EOF

bar

Using sed exclusively:

$ cat << EOF | sed -nE '/foo=/p s/foo=(.+)/\1/'
foo
foo=bar
EOF

sed: -e expression #1, char 9: extra characters after command

What is the cause of the error, and how would one fix it?

1 Answer 1

2

You are trying to do

sed -n -E '/foo=/ s/foo=(.+)/\1/p' <<'END_INPUT'
foo
foo=bar
END_INPUT

Your command had a p after the initial address (the regular expression foo=), which turned it into a complete sed editing command (with the s/... as trailing junk that sed complained about) rather than an address for the s command.

In the command above, /foo=/ is an address for the subsequent s command. The s command would be applied to each line matching the regular expression foo=. The -n option to sed makes it avoid printing the editing buffer after each cycle, which is why we use the p flag with the s command to print the modified line.

However, you could also write that as

sed -n '/foo=./ s/foo=//p' <<'END_INPUT'
foo
foo=bar
END_INPUT

which deletes the foo= bit on each line that has a foo= bit followed by something.

Or, shorter, by letting the s command reuse the regular expression used as the address (and then obviously assuming that we don't require that there is anything after foo=),

sed -n '/foo=/ s///p' <<'END_INPUT'
foo
foo=bar
END_INPUT

Or, even shorter, by recognizing that the s command would not change lines that don't match the regular expression anyway,

sed -n 's/foo=//p' <<'END_INPUT'
foo
foo=bar
END_INPUT

Or, without -n, by deleting all uninteresting lines and modifying only the ones that are interesting and relying on the default output at the end of the cycle,

sed -e '/foo=/!d' -e 's///' <<'END_INPUT'
foo
foo=bar
END_INPUT

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .