2

A test file has the following string:

$ cat testfile
x is a \xtest string

The following script attempts to replace escape sequence: \x occurrences with yy using sed

#!/bin/bash
echo "Printing directly to stdout"
sed -e "s/\\\x/yy/g" testfile
var1=`sed -e "s/\\\x/yy/g" testfile`
echo "Printing from variable"
echo "${var1}"

As it can be seen below, the results are different when it is printed with and without saving to a temporary variable. Could someone help me understand why this happens? I'd want the variable to hold the string that has replaced only \x

Printing directly to stdout
x is a yytest string
Printing from variable
yy is a \yytest string

Platform: macOS

seriousgeek
  • 992
  • 3
  • 13
  • 29
  • 1
    Unrelated to the problem: You should normally put sed expressions in single quotes rather than double quotes. Then you don't need to double the backslashes. – Barmar Dec 08 '21 at 17:58
  • The reason this happens is because backticks process backslash escapes. – Barmar Dec 08 '21 at 17:59
  • @Barmar I see. Would it be better to use `$()` instead of backticks for all command evaluations? Or are there cases where backticks are preferred over `$()`? – seriousgeek Dec 08 '21 at 18:11
  • Backticks are effectively obsolete, there's no time they're preferred. – Barmar Dec 08 '21 at 18:11
  • Unless you need portability to 30 year old systems. – Barmar Dec 08 '21 at 18:13
  • Thanks for clarifying. You could add the response as an answer and I'd be happy to accept it. – seriousgeek Dec 08 '21 at 18:29
  • 1
    You may want to read [Why is $(...) preferred over \`...\` (backticks)?](http://mywiki.wooledge.org/BashFAQ/082) – M. Nejat Aydin Dec 08 '21 at 18:30
  • 1
    Someone else already answered. – Barmar Dec 08 '21 at 18:30
  • This looks like a possible duplicate of ["Why does my Perl one-liner containing an escaped $ not work inside Bash backticks?"](https://stackoverflow.com/questions/37753503/why-does-my-perl-one-liner-containing-an-escaped-not-work-inside-bash-backtick) and/or ["Why can back-quotes and $() for command substitution result in different output?"](https://stackoverflow.com/questions/34150970/why-can-back-quotes-and-for-command-substitution-result-in-different-output) – Gordon Davisson Dec 08 '21 at 18:44
  • @seriousgeek if the answer solved your problem, please accept it. Note that you don't need to upvote it, but please do accept it as it also marks for future readers: "try this, it helped me solve my problem". – OrenIshShalom Dec 09 '21 at 05:05

1 Answers1

0

You should put your command inside a $(...) like that:

#!/bin/bash
echo "Printing directly to stdout"
sed -e "s/\\\x/yy/g" testfile
var1=$(sed -e "s/\\\x/yy/g" testfile)
echo "Printing from variable"
echo "${var1}"
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87