简体   繁体   中英

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?

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

You have to append the content of the next line to your variable:

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

echo $test

Resp. even simpler you could simply read the full file at once into the variable:

test=$(cat file.txt)

resp.

test=$(tr "\n" " " < file.txt)

If you would want to keep the newlines it would be as simple as:

test=<file.txt

Another one:

line=$(< file.txt)
line=${line//$'\n'/ }
test=$(cat file.txt | xargs)
echo $test

I believe it's the simplest method:

text=$(echo $(cat FILE))

But it doesn't preserve multiple spaces/tabs between words.

Use arrays

#!/bin/bash

while read line
do
    a=( "${a[@]}" "$line" )
done < file.txt

echo -n "${a[@]}"

output:

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

See eg tldp section on arrays

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM