How do you use shell script variables as arguments to sed?


What I would like to do is something like the following:


somecommand | sed "$EMAIL"

But I get the following:

sed: -e expression #1, char 2: unknown command: `''

I've tried many variations. I know it just a matter of getting the string quoting right. The reason I'd like to do this is to break a long sed command up for readability. Should I just use a sed script-file (with the -f option) instead?


My actual script is a little more complex:

EMAIL="-e s/SOME THING//g -e s/SOME THING ELSE//g ..."

somecommand | sed "$EMAIL"

After removing the single quotes I get:

sed: -e expression #1, char 18: unknown option to `s'
7/24/2009 5:23:27 PM

Accepted Answer

For this type of quoting problem, you could do one of:

echo SOMETHING | eval sed "$SED_ARG"

What's happening is that in your version, the shell is invoking sed with one argument (the string "-e 's/SOMETHING//g'"), but you want sed to be invoked with two arguments ("-e" and "'s/SOMETHING//g'"). Eval causes the shell to interpret the string the way you want, as does not quoting the argument so that word splitting occurs. Note that this sort of thing is pretty fragile.

7/19/2019 3:35:18 PM

Passing arguments into a sed script shows with an example of writing grep.

#File: sedgrep
sed -n 's/'"$1"'/&/p'

grep can be done as,

sedgrep '[A-Z][A-Z]' <file

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow