shell - Assigning a value having semicolon (';') to a variable in bash -


i'm trying escape ('\') semicolon (';') in string on unix shell (bash) sed. works when directly without assigning value variable. is,

$ echo "hello;" | sed 's/\([^\\]\);/\1\\;/g' hello\; $ 

however, doesn't appear work when above command assigned variable:

$ result=`echo "hello;" | sed 's/\([^\\]\);/\1\\;/g'` $  $ echo $result hello;  $ 

any idea why?

i tried using value enclosed , without quotes didn't help. clue appreciated.

btw, first thought semicolon @ end of string somehow acting terminator , hence shell didn't continue executing sed (if made sense). however, doesn't appear issue. tried using semicolon not @ end of string (somewhere in between). still see same result before. is,

$ echo "hel;lo" | sed 's/\([^\\]\);/\1\\;/g' hel\;lo $ $ result=`echo "hel;lo" | sed 's/\([^\\]\);/\1\\;/g'` $ $ echo $result hel;lo $ 

i find interesting use of back-ticks gives 1 result (your result) , use of $(...) gives result (the wanted result):

$ echo "hello;" | sed 's/\([^\\]\);/\1\\;/g' hello\; $ z1=$(echo "hello;" | sed 's/\([^\\]\);/\1\\;/g') $ z2=`echo "hello;" | sed 's/\([^\\]\);/\1\\;/g'` $ printf "%s\n" "$z1" "$z2" hello\; hello; $ 

if ever needed argument using modern x=$(...) notation in preference older x=`...` notation, it. shell round of backslash interpretation back-ticks. can demonstrate little program use when debugging shell scripts called al (for 'argument list'); can simulate printf "%s\n":

$ z2=`echo "hello;" | al sed 's/\([^\\]\);/\1\\;/g'` $ echo "$z2" sed s/\([^\]\);/\1\;/g $ z1=$(echo "hello;" | al sed 's/\([^\\]\);/\1\\;/g') $ echo "$z1" sed s/\([^\\]\);/\1\\;/g $ z1=$(echo "hello;" | printf "%s\n" sed 's/\([^\\]\);/\1\\;/g') $ echo "$z1" sed s/\([^\\]\);/\1\\;/g $  

as can see, script executed sed differs depending on whether use x=$(...) notation or x=`...` notation.

s/\([^\]\);/\1\;/g            # `` s/\([^\\]\);/\1\\;/g          # $() 

summary

use $(...); easier understand.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -