bash 如何一次性将文件内容读入变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10984432/
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
How to read the file content into a variable in one go?
提问by Shengjie
In Java, if you know for certain a file is very small, you can use readBytes()
method to read the content in one go instead of read it line by line or using buffer.
在Java中,如果你确定一个文件很小,你可以使用readBytes()
方法一次读取内容,而不是逐行读取或使用缓冲区。
Just wondering in shell script, I know we can do something like:
只是想知道在 shell 脚本中,我知道我们可以执行以下操作:
while read line
do
echo $line
LINE = $line
done < "test.file"
echo $LINE
If my test.file is like:
如果我的 test.file 是这样的:
testline1
testline2
testline3
This only gives me the last line to $LINE
. $LINE
contains "testline3".
这只会给我最后一行$LINE
。$LINE
包含“testline3”。
My question is: How can I read the whole file with multiple lines into one single variable,so I can get $LINE="testline1\ntestline2\ntestline3"
?
我的问题是:如何将包含多行的整个文件读入一个变量中,以便获得$LINE="testline1\ntestline2\ntestline3"
?
回答by Paused until further notice.
Process the lines inside the loop instead of after it. If you really need the file in a variable:
处理循环内的行而不是在循环之后。如果您确实需要变量中的文件:
var=$(<file)
回答by Stephen Niedzielski
Another alternative is to use the nice mapfile builtin:
另一种选择是使用漂亮的 mapfile 内置:
mapfile < test.file
echo "${MAPFILE[@]}"
回答by Mark Reed
As another option, you can build an array of lines. If you're running bash 4+, you can use the mapfile
builtin:
作为另一种选择,您可以构建一系列行。如果您运行的是 bash 4+,则可以使用mapfile
内置命令:
mapfile -t lines <test.file
If you want the lines to be output as well as stored you could do something like this:
如果您希望输出和存储行,您可以执行以下操作:
mapfile -t lines < <(tee /dev/tty <test.file)
Then "${lines[0]}"
will be the first line of the file, "${lines[1]}"
the second, and so on. ${#lines[@]}
will be the number of lines; "${lines[@]}"
will be the whole array, while "${lines[*]}"
will be the lines joined together with spaces into one big string.
然后"${lines[0]}"
将是文件的第一行,"${lines[1]}"
第二行,依此类推。${#lines[@]}
将是行数;"${lines[@]}"
将是整个数组,而"${lines[*]}"
行将用空格连接成一个大字符串。
For older versions of bash, you can build the array manually:
对于较旧版本的 bash,您可以手动构建数组:
lines=()
while IFS= read -r line
do
printf '%s\n' "$line"
lines+=("$line")
done < test.file