views:

995

answers:

6

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'
A: 

Remove the single quotes from the value of EMAIL.

EMAIL="-e s/SOMETHING//g"
David Zaslavsky
A: 

remove the single quotes and it should work just fine

ennuikiller
+1  A: 

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
nik
A: 

This worked for me (surround with double quotes) :

 env | sed -n /"$USERNAME"/p
blispr
That's because you're doing something completely different.
Swoogan
+1  A: 

For this type of quoting problem, eval is almost always the solution.

#!/bin/sh
SED_ARG="-e 's/SOMETHING//g'"

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.

William Pursell
A: 

Put everything in single quotes and let the shell eval it later when it's used.

EMAIL='-e s/[email protected]//g'
EMAIL2='-e s/[email protected]//g;s/[email protected]//g'
echo "[email protected] [email protected] [email protected] [email protected]" | sed $EMAIL $EMAIL2
Stephen Paul Lesniewski