0

This BASH script works as expected. I have a variable ($foo) that contains lines of data, I tell bash to separate at new lines, and I loop through the variable.

#!/bin/bash 

foo="
Original Line1
Original Line2
Original Line3
"

IFS=$'\n'

for line in $foo
do
  echo $line
done

As expected, the data is on it's own line.

Original Line1
Original Line2
Original Line3

I add this line to the script, to replace the text "Line2" with "EXAMPLE" in the $foo variable.

foo=$( echo $foo | sed "s|Line2|EXAMPLE|" )

When I run the script, the data is no longer separated on it's own line, and instead prints on a single line. I am not sure how I can replace values in a variable and retain new lines.

Original Line1 Original EXAMPLE Original Line3
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

1 Answers1

3

Your unquoted variable $foo is subject to word splitting by the shell, as explained in detail in Why does my shell script choke on whitespace or other special characters?.

Using quotes will prevent that:

echo "$foo" | sed "s|Line2|EXAMPLE|"

Note that you don't really need sed for such a simple replacement - you could use shell substitution

foo="${foo/Line2/EXAMPLE}"
steeldriver
  • 81,074