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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With