Linux 将文本文件保存在 bash 中的变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9146305/
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
save a text file in a variable in bash
提问by reza
how can I read a text file and save it to a variable in bash ? my code is here :
如何读取文本文件并将其保存到 bash 中的变量?我的代码在这里:
#!/bin/bash
TEXT="dummy"
echo "Please, enter your project name"
read PROJECT_NAME
mkdir $PROJECT_NAME
cp -r -f /home/reza/Templates/Template\ Project/* $PROJECT_NAME
cd $PROJECT_NAME/Latest
TEXT = `cat configure.ac ` ## problem is here !!!
CHANGED_TEXT=${TEXT//ProjectName/$PROJECT_NAME}
echo $CHANGED_TEXT
采纳答案by SiegeX
The issue is that you have an extra space. Assignment requires zero spaces between the =
operator. However, with bash
you can use:
问题是你有一个额外的空间。赋值=
操作符之间需要零空格。但是,bash
您可以使用:
TEXT=$(<configure.ac)
You'll also want to make sure you quote your variables to preserve newlines
您还需要确保引用变量以保留换行符
CHANGED_TEXT="${TEXT//ProjectName/$PROJECT_NAME}"
echo "$CHANGED_TEXT"
回答by Gabriel Grant
Try
尝试
TEXT=`cat configure.ac`
That should work.
那应该工作。
Edit:
编辑:
To clarify, the difference is in the spacing: putting a space after TEXT
causes bash to try to look it up as a command.
澄清一下,区别在于间距:在TEXT
导致 bash 尝试将其作为命令查找后放置一个空格。
回答by Chemaclass
For execute a command and return the result in bash script for save in a variable, for example, you must write the command inner to var=$(command). And you mustn't give spaces between var,'=' and $(). Look at this
例如,执行命令并将结果返回到bash脚本中以保存在变量中,例如,您必须将命令内部写入var=$(command)。而且你不能在 var,'=' 和 $() 之间留空格。看这个
TEXT=$('cat configure.ac')
Now, echo $TEXT
return the content by file configure.ac.
现在,echo $TEXT
通过文件 configure.ac 返回内容。