简体   繁体   English

BASH-从文本文件读取多行

[英]BASH - Reading Multiple Lines from Text File

i am trying to read a text file, say file.txt and it contains multiple lines. 我正在尝试读取一个文本文件,例如file.txt,它包含多行。

say the output of file.txt is file.txt的输出是

$ 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 . 我想将整个输出存储为变量,例如$text
When the variable $text is echoed, the expected output is: 回显变量$text ,预期输出为:

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? 有没有一种方法可以将file.txt中的多行连接为一个长字符串?

You can translate the \\n (newline) to 您可以将\\n (换行符)转换为 (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: 如果行以\\r\\n结尾,则可以执行以下操作:

$ 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. RESP。 even simpler you could simply read the full file at once into the variable: 甚至更简单,您也可以一次将整个文件读入变量:

test=$(cat file.txt)

resp. 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 参见例如关于阵列的tldp部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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