如何在bash中的另一个命令中使用一个命令的结果

How to use the result of a command in another command in bash?

本文关键字:命令 一个 结果 另一个 bash      更新时间:2024-02-03

在循环的每次迭代中,我都试图用从finaltest.txt中提取的行来替换Gruntfile.js的第10行。然而,在下面的代码之后,在我的Gruntfile.js中,第10行被字符串$x取代,而不是它所包含的值。这是我的代码:

#!/bin/bash 
for i in {1..354}
do
    x=`sed -n '$ip' finaltest.txt`
    sed -i '10s/.*/$x/' Gruntfile.js
    grunt
done

此外,grunt命令是运行Gruntfile.js。我在这里做错了什么?

编辑:$x的问题已经在下面给出的答案sed -i "10s~.*~$x~" Gruntfile.js中得到了解决。

然而,剩下的唯一部分是,我希望像finaltest.txt的1p,2p,3p,4p,etc这样的第1、2、3、4行来代替Gruntfile.js的第10行。但是

x=`sed -n '$ip' finaltest.txt

$i不能正常工作,它给出了一个错误。我也试过"$(i)p",但还是一无所获。我应该修改什么?

使用此sed命令:

sed -i "10s~.*~$x~" Gruntfile.js
  • 对shell使用双引号以允许扩展$x
  • 使用备用正则表达式分隔符~,因为您的$x值中包含/

编辑:根据您编辑的问题。你的第一部分也需要在这里双重报价:

x=$(sed "$iq;d" finaltest.txt)