Tuesday, July 1, 2014

Passing arguments to sed

Suppose you have a variable var=25, and a file test.dat which contains the word foo.

$ var=25
$ cat test.dat 
dim
sum
foo
ping
pong

You want to replace all instances of foo in the file to foo$var (=foo25) using sed.

You might think of trying the following:

$ sed 's/foo/foo$var/g' test.dat 
dim
sum
foo$var
ping
pong

Clearly not what you expected. The fix is easy: use double quotes instead of single quotes.

$ sed "s/foo/foo$var/g" test.dat 
dim
sum
foo25
ping
pong

No comments: