Pass variable into sed program

From: Michael F. Stemper (michae...)

I'm in the process of modifying some existing scripts to account for
the fact that the format of their input has changed. The following
piping of multiple sed commands did the trick in one place:

[email protected]$ order=42
[email protected]$ echo 7 | sed "s/,/) ($order,/g" | sed "s/^/($order,/"
| sed "s/$/)/"
(42,7)
[email protected]$ echo 2,3,5,7 | sed "s/,/) ($order,/g" | sed
"s/^/($order,/" | sed "s/$/)/"
(42,2) (42,3) (42,5) (42,7)
[email protected]$

Exactly what I needed. Then, I found another spot in the same script
where I needed the same idiom. I naturally decided to move these three
commands to a sed program:

[email protected]$ cat OldForm.sed
s/,/) ($order,/g
s/^/($order,/
s/$/)/
[email protected]$ echo 7 | sed -f OldForm.sed
($order,7)
[email protected]$

So far, so good.

Then, I tried to actually pass the variable in to the program as a
command-line argument:

[email protected]$ cat OldForm.sed
s/,/) ($1,/g
s/^/($1,/
s/$/)/
[email protected]$ echo 7 | sed -f OldForm.sed $order
sed: can't read 42: No such file or directory
[email protected]$

What's happened is obvious: sed is interpreting the "42" as the
name of a file to read, not as an argument.

I've gone through the O'Reilly book without finding out how to do
this. I've also spent some time searching on-line, and been told
over and over again how to use environment variables in one-liners
(like my opening example had).

What I have been unable to find is any description of how to pass
something into a sed *program*. This seems to be a very basic
action. Is it really true that it's not possible?

--
Michael F. Stemper
What happens if you play John Cage's "4'33" at a slower tempo?

Share |