Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH - Reading Multiple Lines from Text File

i am trying to read a text file, say file.txt and it contains multiple lines.

say the output of file.txt is

$ cat file.txt
this is line 1

this is line 2

this is line 3

I want to store the entire output as a variable say, $text.
When the variable $text is echoed, the expected output is:

this is line 1 this is line 2 this is line 3

my code is as follows

while read line
do
    test="${LINE}"
done < file.txt

echo $test

the output i get is always only the last line. Is there a way to concatenate the multiple lines in file.txt as one long string?

like image 696
John Marston Avatar asked Oct 29 '25 07:10

John Marston


1 Answers

You can translate the \n(newline) to (space):

$ text=$(tr '\n' ' ' <file.txt)
$ echo $text
this is line 1 this is line 2 this is line 3

If lines ends with \r\n, you can do this:

$ text=$(tr -d '\r' <file.txt | tr '\n' ' ')
like image 107
kev Avatar answered Oct 31 '25 20:10

kev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!