BASH - 从文本文件中读取多行

Joh*_*ton 4 bash text concatenation

我正在尝试读取一个文本文件,例如 file.txt,它包含多行。

说输出file.txt

$ cat file.txt
this is line 1

this is line 2

this is line 3
Run Code Online (Sandbox Code Playgroud)

我想将整个输出存储为变量,例如$text.
当变量$text被回显时,预期输出为:

this is line 1 this is line 2 this is line 3
Run Code Online (Sandbox Code Playgroud)

我的代码如下

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

echo $test
Run Code Online (Sandbox Code Playgroud)

我得到的输出始终只是最后一行。有没有一种方法可以将 file.txt 中的多行连接为一个长字符串?

kev*_*kev 5

您可以将\n(换行符)翻译为(空格):

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

如果行以 结尾\r\n,您可以这样做:

$ text=$(tr -d '\r' <file.txt | tr '\n' ' ')
Run Code Online (Sandbox Code Playgroud)