Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use output of one command as replacement text in sed

Tags:

bash

unix

sed

I have a .env file with a bunch of key-value pairs like so:

NAME=John Doe
CITY=Timbuctoo
CSS=<some value>
PORT=3000

It is the third line I'm trying to change programmatically. is a dynamically-generated md5 hash and each time I run the command, it needs to be replaced by a new hash. This is how I'm generating the hash:

$ date +%s | md5sum | cut -d' ' -f 1

And I wish to use the output of the above command as the replacement text when using sed. But can't figure out how to make it work. The following is the solution I have so far which is far from complete:

$ date +%s | md5sum | cut -d' ' -f 1 | sed -i.bak 's/^\(CSS=\).*/replacement/' ~/nano/.env

What should put in place of "replacement" to ensure the original value gets replaced by the value returned by cut?

like image 817
TheLearner Avatar asked Aug 03 '17 12:08

TheLearner


People also ask

How do you use sed command to replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

Which sed command is used for replacement?

Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.

How do you replace a variable in a file using sed?

In this syntax, you just need to provide the string you want to replace at the old string and then the new string in the inverted commas. After that, provide the file in which you want to find and replace the mentioned string.


2 Answers

You can simply use

sed -i.bak "s/^\(CSS=\).*/$(date +%s | md5sum | cut -d' ' -f 1)/" ~/nano/.env

The important thing is to use " instead of ' so that bash substitutes the subshell command $(...).

like image 110
Eduard Itrich Avatar answered Oct 22 '22 23:10

Eduard Itrich


You could use xargs with I and a place-holder {} to store the value stdin and pass it over to sed as

date +%s | md5sum | cut -d' ' -f 1 | xargs -I {} sed -i.bak 's/^\(CSS=\).*/CSS={}/' file

But I would wisely avoid introducing another pipe-line and would use a separated command for sed

newHash=$(date +%s | md5sum | cut -d' ' -f 1); sed -i.bak "s/^\(CSS=\).*/CSS=${newHash}/" file 
like image 27
Inian Avatar answered Oct 22 '22 23:10

Inian