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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10211811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:03:57  来源:igfitidea点击:

BASH - Reading Multiple Lines from Text File

bashtextconcatenation

提问by John Marston

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

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

say the output of file.txtis

说输出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.
When the variable $textis echoed, the expected output is:

我想将整个输出存储为一个变量,比如$text.
当变量$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 中的多行连接为一个长字符串?

回答by kev

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

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

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

回答by Fritz G. Mehner

Another one:

另一个:

line=$(< file.txt)
line=${line//$'\n'/ }

回答by Karthi Kulandaivelu

test=$(cat file.txt | xargs)
echo $test

回答by bmk

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

回答by yazu

I believe it's the simplest method:

我相信这是最简单的方法:

text=$(echo $(cat FILE))

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

但它不会在单词之间保留多个空格/制表符。

回答by Fredrik Pihl

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 e.g. tldp section on arrays

参见例如关于数组的 tldp 部分