Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed with command line argument?

Tags:

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

sed 's/brad/pitt/g'

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

sed s/$1/pitt/g

While this command is working, what I would like to know is how can I do this command without removing the quotes, since I might have some content in the replacement string which needs the quotes.

I am not so confident with the quotes and that is why I want to see how things will work with a little tweaking?

like image 654
Dude Avatar asked Feb 14 '13 22:02

Dude


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

like image 99
Karoly Horvath Avatar answered Oct 14 '22 15:10

Karoly Horvath


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
like image 22
Joshua Clayton Avatar answered Oct 14 '22 16:10

Joshua Clayton