Reputation: 476709
Say I have a bash
script, that first parses parameters/files. As a result, the script generates the following string:
args="-e 's/\\\$foo\\b/bar/gi' -e 's/\\\$baz\\b/qux/gi'"
Now I want to feed the resulting string (-e 's/\$foo\b/bar/gi' -e 's/\$baz\b/qux/gi'
) to sed in order to perform search and replace on for instance the following file:
Hello $foo, hello $baz
If one uses sed -e 's/\$foo\b/bar/gi' -e 's/\$baz\b/qux/gi'
, it returns:
Hello bar, hello qux
If however one calls:
sed $args
it gives an error:
sed: -e expression #1, char 1: unknown command: `''
How can I programmatically feed a sequence of parameters to sed
?
Upvotes: 4
Views: 104
Reputation:
You can simplify it into one string, to make it easier on the quoting:
sedargs="s/\$foo\b/bar/gi;s/\$baz\b/qux/gi"
sed "${sedargs}" <<< "Hello \$foo, hello \$baz"
Upvotes: 1
Reputation: 785256
Avoid all the crazy escaping and declare args
variable as a shell array:
args=(-e 's/\$foo\b/bar/gi' -e 's/\$baz\b/qux/gi')
and then use it in sed
as:
s='Hello $foo, hello $baz'
echo "$s" | sed "${args[@]}"
Hello bar, hello qux
Upvotes: 2