Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
like image 539
Swoogan Avatar asked Jul 24 '09 16:07

Swoogan


2 Answers

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.

like image 99
William Pursell Avatar answered Nov 15 '22 18:11

William Pursell


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
like image 29
nik Avatar answered Nov 15 '22 18:11

nik