sed – using variables containing "/"

Johnny Rosenberg gurus.knugum at gmail.com
Sun Feb 12 18:53:35 UTC 2012


Text in terminal below as typed, except text inside [], which can be
either a keyboard short-cut or a comment.

––– Terminal input/output–––
MyPrompt $ cat > testfile
Replace the next line with something:
$1
Here is another line, don't replace it.
[Ctrl+d]
MyPrompt $ MyVar="/"
MyPrompt $ echo $MyVar
/
MyPrompt $ cat testfile | sed -e "s/\$1/$MyVar/"
sed: -e uttryck #1, tecken 7: flaggan okänd för "s" [In English,
something like: ”sed: -e expression #1, character 7: flag unknown for
"s"”]
MyPrompt $ cat testfile | sed -e "s@\$1@$MyVar@"
Replace the next line with something:
/
Here is another line, don't replace it.
MyPrompt $
––– End of terminal input/output –––

So, if the variable MyVar contains a ”/”, sed will fail and a
workaround is to use another character instead of the ”/” character
for sed, like in this case, ”@”.
Is this the only workaround in this case or is there a more elegant
one? The variable ”MyVar” must not be changed in any way, other than
that, everything is allowed, I suppose…


Kind regards

Johnny Rosenberg
ジョニー・ローゼンバーグ




More information about the ubuntu-users mailing list