Linux 如何读取文件并将其重定向到变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4749905/
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 can I read a file and redirect it to a variable?
提问by Tom Brito
I have a file with a word written on it. I want my script to put that word in a variable.
我有一个文件,上面写着一个字。我希望我的脚本把这个词放在一个变量中。
How can I do that?
我怎样才能做到这一点?
采纳答案by wich
in several of a million ways...
以百万分之几的方式......
simplest is probably
最简单的可能是
my_var=$(cat my_file)
If you use bash and you want to get spiffy you can use bash4's mapfile, which puts an entire file into an array variable, one line per cell
如果您使用 bash 并且想要变得漂亮,您可以使用 bash4 的 mapfile,它将整个文件放入一个数组变量中,每个单元格一行
mapfile my_var < my_file
回答by jamesbtate
var="`cat /path/to/file`"
This is the simple way. Be careful with newlines in the file.
这是简单的方法。小心文件中的换行符。
var="`head -1 /path/to/file`"
This will only get the first line and will never include a newline.
这只会得到第一行,永远不会包括换行符。
回答by orlp
I think it will strip newlines, but here it is anyway:
我认为它会去除换行符,但无论如何都是这样:
variable=$(cat filename)
回答by giles123
I think the easiest way is something like
我认为最简单的方法是
$ myvar=`cat file`
回答by Diego Torres Milano
The simplest way is probably:
最简单的方法大概是:
var=$(< file)
which doesn't create a new process.
这不会创建新进程。