Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace "\n" string with a new line in Unix Bash script

Cannot seem to find an answer to this one online...

I have a string variable (externally sourced) with new lines "\n" encoded as strings.

I want to replace those strings with actual new line carriage returns. The code below can achieve this...

echo $EXT_DESCR | sed 's/\\n/\n/g'

But when I try to store the result of this into it's own variable, it converts them back to strings

NEW_DESCR=`echo $EXT_DESCR | sed 's/\\n/\n/g'`

How can this be achieved, or what I'm I doing wrong?

Here's my code I've been testing to try get the right results

EXT_DESCR="This is a text\nWith a new line"
echo $EXT_DESCR | sed 's/\\n/\n/g'

NEW_DESCR=`echo $EXT_DESCR | sed 's/\\n/\n/g'`
echo ""
echo "$NEW_DESCR"
like image 374
Skytunnel Avatar asked Aug 28 '18 19:08

Skytunnel


People also ask

How do I add a new line to a string in bash?

Printing Newline in Bash Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.

How do I replace a line in a bash script?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


2 Answers

No need for sed, using parameter expansion:

$ foo='1\n2\n3'; echo "${foo//'\n'/$'\n'}"  
1
2
3

With bash 4.4 or newer, you can use the E operator in ${parameter@operator}:

$ foo='1\n2\n3'; echo "${foo@E}"
1
2
3
like image 186
PesaThe Avatar answered Sep 19 '22 18:09

PesaThe


Other answers contain alternative solutions. (I especially like the parameter expansion one.)

Here's what's wrong with your attempt:

In

echo $EXT_DESCR | sed 's/\\n/\n/g'

the sed command is in single quotes, so sed gets s/\\n/\n/g as is.

In

NEW_DESCR=`echo $EXT_DESCR | sed 's/\\n/\n/g'`

the whole command is in backticks, so a round of backslash processing is applied. That leads to sed getting the code s/\n/\n/g, which does nothing.

A possible fix for this code:

NEW_DESCR=`echo $EXT_DESCR | sed 's/\\\\n/\\n/g'`

By doubling up the backslashes, we end up with the right command in sed.

Or (easier):

NEW_DESCR=$(echo $EXT_DESCR | sed 's/\\n/\n/g')

Instead of backticks use $( ), which has less esoteric escaping rules.

Note: Don't use ALL_UPPERCASE for your shell variables. UPPERCASE is (informally) reserved for system variables such as HOME and special built-in variables such as IFS or RANDOM.

like image 41
melpomene Avatar answered Sep 17 '22 18:09

melpomene