What I would like to do is something like the following:
#!/bin/sh
EMAIL="-e 's/SOMETHING//g'"
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?
UPDATE:
My actual script is a little more complex:
#!/bin/sh
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With