Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

replace

sed

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.

like image 367
BenMorel Avatar asked Jun 25 '13 15:06

BenMorel


People also ask

How do you return a value from a command?

The return value of a command is stored in the $? variable. The return value is called exit status. This value can be used to determine whether a command completed successfully or unsuccessfully.

How do I replace text in a file in bash?

To replace content in a file, you must search for the particular file string. The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


2 Answers

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; 
like image 172
fedorqui 'SO stop harming' Avatar answered Sep 30 '22 02:09

fedorqui 'SO stop harming'


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.

awk 'NR==FNR {a[NR]=$0;next}     {print}     /Insert index here/ {for (i=1; i <= length(a); i++) { print a[i] }}'     <(ls -l) template.file 

or

sed '/^Insert after this$/r'<(ls -l) template.file 
like image 41
Walter A Avatar answered Sep 30 '22 01:09

Walter A