bash 如何用文本文件中的命令输出替换值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17301683/
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 to replace a value with the output of a command in a text file?
提问by Benjamin
I have a file that contains:
我有一个包含以下内容的文件:
<?php return 0;
I want to replace in bash, the value 0
by the current timestamp.
我想用 bash 替换0
当前时间戳的值。
I know I can get the current timestamp with:
我知道我可以通过以下方式获取当前时间戳:
date +%s
And I can replace strings with sed
:
我可以用以下内容替换字符串sed
:
sed 's/old/new/g' input.txt > output.txt
But how to combine the two to achieve what I want? Solutions not involving sed
and date
are welcome as well, as long as they only use shell tools.
但是如何将两者结合起来实现我想要的呢?解决方案不涉及sed
,并date
欢迎为好,只要他们只使用shell工具。
回答by fedorqui 'SO stop harming'
In general, do use this syntax:
通常,请使用以下语法:
sed "s/<expression>/$(command)/" file
This will look for <expression>
and replace it with the output of command
.
这将查找<expression>
并替换为command
.
For your specific problem, you can use the following:
对于您的具体问题,您可以使用以下方法:
sed "s/0/$(date +%s)/g" input.txt > output.txt
This replaces any 0
present in the file with the output of the command date +%s
. Note you need to use double quotes to make the command in $()
be interpreted. Otherwise, you would get a literal $(date +%s)
.
这将0
用命令的输出替换文件中的任何内容date +%s
。请注意,您需要使用双引号来$()
解释命令。否则,你会得到一个文字$(date +%s)
.
If you want the file to be updated automatically, add -i
to the sed command: sed -i "s/...
. This is called in-place editing.
如果您希望文件自动更新,请添加-i
到 sed 命令:sed -i "s/...
. 这称为就地编辑。
Test
测试
Given a file with this content:
给定一个包含此内容的文件:
<?php return 0;
Let's see what it returns:
让我们看看它返回什么:
$ sed "s/0/$(date +%s)/g" file
<?php return 1372175125;
回答by Walter A
When the replacement string has newlines and spaces, you can use something else.
We will try to insert the output of ls -l
in the middle of some template file.
当替换字符串有换行符和空格时,您可以使用其他内容。我们将尝试ls -l
在一些模板文件的中间插入输出。
awk 'NR==FNR {a[NR]=sed '/^Insert after this$/r'<(ls -l) template.file
;next}
{print}
/Insert index here/ {for (i=1; i <= length(a); i++) { print a[i] }}'
<(ls -l) template.file
or
或者
##代码##