Jonas
Jonas

Reputation: 675

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,

Upvotes: 1

Views: 3172

Answers (3)

Tom
Tom

Reputation: 16188

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.

Upvotes: 1

P.P
P.P

Reputation: 121357

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/'

Upvotes: 2

Kent
Kent

Reputation: 195039

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/

Upvotes: 1

Related Questions