Nico Rodsevich
Nico Rodsevich

Reputation: 2585

Save command output in string variable keeping newlines

I have a script that transforms a file's data, in order to work more efficiently I want to alter the data in memory and then dump it to the file. Supose I want to modify a file that contains this:

> This is a line
> this is other line

I use a sed command to replace the '>' symbols with '#' ones:

transform_output=$(eval "sed ${sed_args[@]} $file" 2>&1)
echo -e $transform_output

I get the output:

# This is a line # this is other line

rather than the output I would like to have wich is:

# This is a line
# this is other line
  1. How do I save the output in the string variable keeping the newlines?
  2. How could I add a line at the begining of the variable that contains "#ADDED LINE#" and save that in a file?

(the file I want to obtain would be):

#ADDED LINE#
# This is a line
# this is other line

Thanks in advance

Upvotes: 5

Views: 4816

Answers (1)

Barmar
Barmar

Reputation: 782683

  1. Quoting is used to prevent word-splitting at whitespace:

    echo -e "$transform_output"

  2. Group the command with another echo:

    { echo "#ADDED LINE#"; echo -e "$transform_output" } > file

Upvotes: 6

Related Questions