Home > Software engineering >  sed results different when using bash variables
sed results different when using bash variables

Time:12-11

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

CodePudding user response:

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}"
  • Related