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

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

#!/bin/sh
SED_ARG="-e 's/SOMETHING//g'"
echo SOMETHING | eval sed "$SED_ARG"
echo SOMETHING | 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.


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

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

grep can be done as,

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