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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Can you explain a bit on what is happening.
Quoting is of utmost importance in Unix shells. Without quotes shell doesn't apply any expansion rules and treats new lines as space.
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.
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"

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.