Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating two string variables in bash appending newline

Tags:

linux

bash

shell

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?

like image 968
Aman Deep Gautam Avatar asked Aug 30 '13 14:08

Aman Deep Gautam


People also ask

How do I add a new line to a string in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.

How do I concatenate string variables in bash?

The += Operator in Bash Bash is a widely used shell in Linux, and it supports the '+=' operator to concatenate two variables. As the example above shows, in Bash, we can easily use the += operator to concatenate string variables.

How do I concatenate a new line in a string?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.


1 Answers

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 
like image 183
anubhava Avatar answered Oct 14 '22 15:10

anubhava