Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - How to replace a value with the output of a command in a text file?

I have a file that contains:

<?php return 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

And I can replace strings with 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In general, do use this syntax:

sed "s/<expression>/$(command)/" file

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

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).

If you want the file to be updated automatically, add -i to the sed command: sed -i "s/.... This is called in-place editing.


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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...