如何一次性将文件内容读入变量? [英] How to read the file content into a variable in one go?

查看:49
本文介绍了如何一次性将文件内容读入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如果您确定某个文件非常小,则可以使用 readBytes()方法一次性读取内容,而不必一行一行地读取内容或使用缓冲区.

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.

只是想知道shell脚本,我知道我们可以做类似的事情:

Just wondering in shell script, I know we can do something like:

    while read line
    do
      echo $line
      LINE = $line
    done < "test.file"
    echo $LINE

如果我的test.file是这样的:

If my test.file is like:

testline1
testline2
testline3

这仅给了我 $ LINE 的最后一行. $ LINE 包含"testline3".

This only gives me the last line to $LINE. $LINE contains "testline3".

我的问题是:如何将具有多行的整个文件读入一个变量,以便获得 $ LINE ="testline1 \ ntestline2 \ ntestline3" ?

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"?

推荐答案

处理循环内部的行,而不是处理循环之后的行.如果您确实需要变量中的文件:

Process the lines inside the loop instead of after it. If you really need the file in a variable:

var=$(<file)

这篇关于如何一次性将文件内容读入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆