mikelplhts
mikelplhts

Reputation: 1221

Shell substring with sed in a variable

I have tried this command in bash linux

echo "example=value" | sed "s/^example=\(.*\)$/\1/"

The output is value. But if I put it in a variable, it doesn't work.

For example:

var="example=value" | sed "s/^example=\(.*\)$/\1/"
echo $var

The output is nothing. What wrong?

Upvotes: 2

Views: 1333

Answers (3)

Benjamin W.
Benjamin W.

Reputation: 52142

You can do this without sed, using shell parameter expansion:

$ var="example=value"
$ var="${var#*=}"
$ echo "$var"
value

Upvotes: 0

Daniel
Daniel

Reputation: 783

Do it like this:

var=$(echo example=value | sed "s/^example=\(.*\)$/\1/")
echo $var

Upvotes: 4

riteshtch
riteshtch

Reputation: 8769

assigning a variable doesn't pass the value to sed via pipe.

You can pass while assigning like this:

var="example=value" && echo "$var" | sed "s/^example=\(.*\)$/\1/"

or use a sub shell like this:

var=$(echo "example=value" | sed "s/^example=\(.*\)$/\1/")

Upvotes: 1

Related Questions