Using sed with command line argument?

There are two ways you can do it:

1) use double quotes

 sed "s/$1/pitt/g"

2) construct the command as a string and run it with eval

SEDCMD="s/$1/pitt/g"
eval sed $SEDCMD

The eval method works and is very flexible, but is considered dangerous, because it is vulnerable to code injection. If you don't trust your inputs, don't use #2

UPDATE: The comments are right, there is no benefit to using eval (I used to use eval with sed this way all the time, and I'm not sure why....) building sed strings for later use, however, is powerful: so I'll add a new 3) and leave 2 for folks to mock

3) construct the command as a string and then run 1 or more of them

FOO='s/\(.*\)bar/\1baz/'
BAR="s/$1/pitt/g"
sed -e $BAR -e $FOO <infile >outfile

You can sed "s/$1/pitt/g" or sed 's/'$1'/pitt/g'

or, if the command line argument is not a simple word, sed 's/'"$1"'/pitt/g'.

Tags:

Bash

Sed