33

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?

0

3 Answers 3

35

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
3
  • Thank you. Can you explain a bit on what is happening. Commented Aug 30, 2013 at 14:59
  • 3
    Quoting is of utmost importance in Unix shells. Without quotes shell doesn't apply any expansion rules and treats new lines as space.
    – anubhava
    Commented Aug 30, 2013 at 15:01
  • 4
    Without the quotes, any white space (including newlines) in the expansion of $final_list is treated as a word separator, not literal characters to print. echo receives only 3 arguments, the actual URLs. With quotes, echo receives a single argument, the string that contains urls and the newlines that separate them.
    – chepner
    Commented Aug 30, 2013 at 16:28
3

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

echo "$final_list"
1

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...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.