如何用文本文件中的命令输出替换值? [英] How to replace a value with the output of a command in a text file?
问题描述
我有一个文件,其中包含:
I have a file that contains:
<?php return 0;
我想用当前时间戳替换bash值0
.
I want to replace in bash, the value 0
by the current timestamp.
我知道我可以通过以下方式获取当前时间戳:
I know I can get the current timestamp with:
date +%s
我可以用sed
替换字符串:
sed 's/old/new/g' input.txt > output.txt
但是如何结合两者来实现我想要的呢?只要不使用sed
和date
的解决方案,只要它们仅使用Shell工具,也将受到欢迎.
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.
推荐答案
通常,请使用以下语法:
In general, do use this syntax:
sed "s/<expression>/$(command)/" file
这将查找<expression>
,并将其替换为command
的输出.
This will look for <expression>
and replace it with the output of command
.
对于您的特定问题,可以使用以下内容:
For your specific problem, you can use the following:
sed "s/0/$(date +%s)/g" input.txt > output.txt
这将用命令date +%s
的输出替换文件中存在的任何0
.请注意,您需要使用双引号使$()
中的命令得到解释.否则,您将得到文字$(date +%s)
.
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)
.
如果要自动更新文件,请将-i
添加到sed命令:sed -i "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.
提供具有以下内容的文件:
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;
这篇关于如何用文本文件中的命令输出替换值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!