Aman Deep Gautam
Aman Deep Gautam

Reputation: 8787

Concatenating two string variables in bash appending newline

I have a variable final_list which is appended by a variable url in a loop as:

while read url; do
    final_list="$final_list"$'\n'"$url"
done < file.txt

To my surprise the \n is appended as an space, so the result is:

url1 url2 url3

while I wanted:

url1
url2
url3

What is wrong?

Upvotes: 33

Views: 52892

Answers (3)

Venkatesha K
Venkatesha K

Reputation: 176

Adding one more possible option if anyone like to try.

With String Value :

Command : echo "This is the string I want to print in next line" | tr " " "\n"

Output :

This
is
the
string
I
want
to
print
in
next
line

With Vars used :

finallist="url1 url2 url3"          
url="url4 url5"                     
echo "$finallist $url" | tr " " "\n"

Output :

url1
url2
url3
url4
url5

if you like to have few words to be in one line and few in next line, try with different separater. (like - or : or ; or etc...)

Upvotes: 1

Emo Mosley
Emo Mosley

Reputation: 535

It may depend on how you're trying to display the final result. Try outputting the resulting variable within double-quotes:

echo "$final_list"

Upvotes: 3

anubhava
anubhava

Reputation: 786091

New lines are very much there in the variable "$final_list". echo it like this with double quotes:

echo "$final_list"
url1
url2
url3

OR better use printf:

printf "%s\n" "$final_list"
url1
url2
url3

Upvotes: 35

Related Questions