如何在sed中使用backtick命令结果?

izz

我想用源文件中的git rev-parse HEAD模板字符串替换代码中的版本%VERSION%

为简单起见,我将date在此问题中将其用作版本命令。

给定 test.txt

$ echo "This is test-%VERSION%." > test.txt
$ cat test.txt
This is test-%VERSION%.

期望

This is test-Sat Dec  2 16:48:59 +07 2017.

这些都是失败的尝试

$ echo "This is test-%VERSION%." > test.txt
$ sed -i 's/%VERSION/`date`/' test.txt && cat test.txt
This is test-`date`%.

$ echo "This is test-%VERSION%." > test.txt
$ DD=`date` sed -i 's/%VERSION/$DD/' test.txt && cat test.txt
This is test-$DD%.

$ echo "This is test-%VERSION%." > test.txt
$ DD=`date` sed -i "s/%VERSION/$DD/" test.txt && cat test.txt
This is test-%.

我真的需要使用xargs吗?

亚诺斯

您可以嵌入$(...)双引号,但不能嵌入单引号:

sed -i "s/%VERSION%/$(date)/" test.txt && cat test.txt

(与更好`...`但不要使用该过时的语法相同$(...)。)


顺便说一句,用于测试目的,最好使用sed-i,所以原来的文件不会被修改:

sed "s/%VERSION%/$(date)/" test.txt

作为附带说明,这是一个完全不同的讨论,但在这里值得一提。这看起来像应该工作,但不起作用,并且您可能想知道为什么:

DD=$(date) sed -i "s/%VERSION%/$DD/" test.txt && cat test.txt

为什么不起作用?因为在执行命令时会评估中$DD嵌入"..."当时的价值DD不能设置为输出$(date)在中"...",它将具有执行命令之前所具有的任何值。在此sed过程中,DD带有输出的值$(date)是可见的,但sed不使用它,因为为什么会这样。"..."传递到sed由壳评估,不是sed

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章