Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically feed parameters to sed

Tags:

bash

shell

sed

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?

like image 868
Willem Van Onsem Avatar asked Sep 13 '25 00:09

Willem Van Onsem


1 Answers

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
like image 130
anubhava Avatar answered Sep 14 '25 16:09

anubhava