Is it possible to pass arguments to a sed script

sed

Consider a simple sed script foo-to-bar.sed:

s/foo/bar/

and the simple invocation:

sed -f foo-to-bar.sed some-file.txt

Now, let's say I want to customize the replacement string (bar in this case) and pass it as an argument to the sed script. Is that possible?

NOTE: I'm aware that I can get rid of the sed script and use shell variables inline. I'm interested specifically about passing arguments into the sed script. I couldn't find anything in the documentation, but I still hope that I'm missing something.

Best Answer

Since it seems like indeed there's no way to pass in arguments, the best workaround I can think of is to use an intermediate placeholder that is replaced from the command line. foo-to-bar.sed:

s/foo/#ARG1#/

Invocation:

sed -f foo-to-bar.sed -e "s/#ARG1#/bar/g" some-file.txt

Explanation: foo is first replaced with #ARG1# and then with bar passed from the command line. Note that it's important to have the -e after -f. Also there's nothing special about the # delimiter, use anything that wouldn't normally appear in the file.

Related Question