将文本文件保存在bash中的变量中

时间:2021-07-23 15:46:02

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

3 个解决方案

#1


14  

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"

#2


3  

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尝试将其作为命令查找之后放置一个空格。

#3


1  

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脚本中以保存在变量中,必须将命令inner写入var = $(command)。并且你不能在var,'='和$()之间给出空格。看这个

TEXT=$('cat configure.ac')

Now, echo $TEXT return the content by file configure.ac.

现在,echo $ TEXT按文件configure.ac返回内容。

#1


14  

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"

#2


3  

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尝试将其作为命令查找之后放置一个空格。

#3


1  

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脚本中以保存在变量中,必须将命令inner写入var = $(command)。并且你不能在var,'='和$()之间给出空格。看这个

TEXT=$('cat configure.ac')

Now, echo $TEXT return the content by file configure.ac.

现在,echo $ TEXT按文件configure.ac返回内容。