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
?
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.
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.
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.
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 $(...)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With