简体   繁体   中英

bash : sed : regex in variable

I'm getting totally crazy with the following script.

The following command works as expected :

echo a | sed 's/a/b/'

Output :

b

But this script doesn't :

test="'s/a/b/'"
echo a | sed $test

Output :

sed: -e expression #1, char 1: unknown command : `''

I should really be stupid, but I don't see what I am missing.

Thanks,

test="'s/a/b/'"
echo a | sed $test

is equivalent to:

test="'s/a/b/'"
echo a | sed "'s/a/b/'"

Obviously sed doesn't understand the command with both " and ' , It interprets ' as a command. You can use either one of them:

test='s/a/b/'

Or

test='s/a/b/'

you may want this:

kent$  test="s/a/b/"         

kent$  echo a | sed ${test}
b

or

kent$  echo a | sed $test  
b

or

test=s/a/b/

This is because your double wrapping your string. test="'s/a/b'" . Sed then gets 's/a/b/' as literal string. You only want sed to receive s/a/b/ .
You only need to wrap the string in one set of quotes , otherwise the inner set of quotes will be interpreted as part of the argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM