'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?
Solution 1:[1]
It may depend on how you're trying to display the final result. Try outputting the resulting variable within double-quotes:
echo "$final_list"
Solution 2:[2]
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...)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Emo Mosley |
| Solution 2 |
