Using sed with a command line argument?

I need to run a sed command like this as part of a shell script

sed 's / brad / pitt / g'

I have to provide brad as a command line argument and run a command like this

sed s / $ 1 / pitt / g

While this command is working, I would like to know how I can execute this command without removing the quotes, since I may have some content in the replacement string that needs quotes.

I'm not so sure about the quotes, and that’s why I want to see how everything works with a little tweaking?

+6
source share
2 answers

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' .

+15
source

There are two ways to do this:

1) use double quotes

  sed "s/$1/pitt/g" 

2) build 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 it is considered dangerous because it is vulnerable to code injection. If you do not trust your inputs, do not use # 2

UPDATE: the comments are right, there is no use for using eval (I used to use eval all the time with sed this way, and I'm not sure why ....) builds a series of lines for later use, however, is powerful: so I will add new 3) and leave 2 for folk to mock

3) create 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 
+3
source

All Articles