Need to convert \n character to newline in UNIX.

I have a variable like below:

str1="10.9.11.128\n-rwxr-xr-x user1 2019-12-29 17:53 /var/branch/custom/tg.xml 286030210\n10.9.12.129\n-rwxr-xr-x user1 2019-12-29 17:53 /app/branch/custom/tg.xml 286030210\n10.9.20.130\n-rwxr-xr-x user1 2019-12-29 17:53 /web/branch/custom/tg.xml 286030210"

I redirect this string to a file and then access the file using web browser like below.

echo $str1 > text.txt

http://localhost/text.txt

I see the output in the web browser as:

10.9.11.128\n-rwxr-xr-x user1 2019-12-29 17:53 /var/branch/custom/tg.xml 286030210\n10.9.12.129\n-rwxr-xr-x user1 2019-12-29 17:53 /app/branch/custom/tg.xml 286030210\n10.9.20.130\n-rwxr-xr-x user1 2019-12-29 17:53 /web/branch/custom/tg.xml 286030210

However, my requirement is to convert \n to a new line to the text.txt file in the browser should look like this:

10.9.11.128
-rwxr-xr-x user1 2019-12-29 17:53 /var/branch/custom/tg.xml 286030210
10.9.12.129
-rwxr-xr-x user1 2019-12-29 17:53 /app/branch/custom/tg.xml 286030210
10.9.20.130
-rwxr-xr-x user1 2019-12-29 17:53 /web/branch/custom/tg.xml 286030210

Can you please suggest how can I change my string str1 to meet expected output ? I'm looking for a POSIX solution especially not an awk solution.

echo $str1 | sed 's/\\n/\n/g' > text.txt
1 Like

Hi
just add option

echo -e $str1 > text.txt
1 Like

Works :slight_smile: Thank you.

Be careful with echo and with unquoted variables in command arguments!
From [Tip] A better echo

# Portable echo -e
echo_e() {
  ( IFS=" "; printf "%b\n" "$*" )
}

echo_e "$str1"

Or use printf directly

printf "%b\n" "$str1"
3 Likes

You could use this bash ism (?; don't know about other shells) in the first place. man bash :

str1=$'10.9.11.128\n-rwxr-xr-x user1 2019-12-29 17:53 /var/branch/custom/tg.xml 286030210\n10.9.12.129\n-rwxr-xr-x user1 2019-12-29 17:53 /app/branch/custom/tg.xml 286030210\n10.9.20.130\n-rwxr-xr-x user1 2019-12-29 17:53 /web/branch/custom/tg.xml 286030210'
echo "$str1"
10.9.11.128
-rwxr-xr-x user1 2019-12-29 17:53 /var/branch/custom/tg.xml 286030210
10.9.12.129
-rwxr-xr-x user1 2019-12-29 17:53 /app/branch/custom/tg.xml 286030210
10.9.20.130
-rwxr-xr-x user1 2019-12-29 17:53 /web/branch/custom/tg.xml 286030210
1 Like

Would changing echo to printf work?

printf "$str1" > text.txt

Robin

Perhaps yes, if $str1 doesn't have % characters.

The perfect example to RudiC's post #6...
OSX 10.14.6 default bash terminal...

Last login: Fri Jan  3 13:50:35 on console
AMIGA:amiga~> set
...
IFS=$' \t\n'
...
AMIGA:amiga~> _