How to escape single quotes in Sed one-liners

A few days ago, a co-worker came to me with a Sed question. He had a line like this in a file called myfile:

MYVAR='MYVALUE'

He needed to get MYVALUE (without the single quotes around it) into a shell variable and he wanted to use a Sed one-liner.

After a few failed attempts on escaping the single quotes, I decided to wrap the Sed expression with double quotes and it worked for me:

$ sed "s/^MYVAR='\(.*\)'\$/\1/" myfile
MYVALUE

Unfortunately, this did not work for him for some reason that perhaps was related to the fact that he was working in AIX. This alternative method, however, worked for both of us:

$ sed 's/^MYVAR='\''\(.*\)'\''$/\1/' myfile
MYVALUE

After this, assigning this value to a shell variable is as easy as capturing the output using back ticks:

$ SHELLVAR=`sed 's/^MYVAR='\''\(.*\)'\''$/\1/' myfile`
$ echo $SHELLVAR
MYVALUE
  1. Mojito says:

    ***thanks***

    (Y abrazos!) :-)

  1. There are no trackbacks for this post yet.

Leave a Reply