Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sed replace with regex whole line

There are two files:

file1:

dir='/root/path/to/somewhere/'
sed -zre "s|dir=(.*)'$|dir='$(echo $dir)'|g" -i file2

file2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dir='/blah/blah/'

I want to do this:

find a line having dir=(.*) and replace with the value of $dir

I run bash file1, but it doesn’t replace anything in `file21.

>Solution :

Following sed should work for you:

sed -i "s|dir=.*|dir='$dir'|" file2

Note removal of incorrect options -zre in this command and removal of redundant command substitution from your sed command.

Specifically problematic is use of -z that slurps complete input file in a single line of text thus failing to match '$ since closing single quote is not the last character in file.

If you want to avoid repeating dir= 2 times then use a capture group:

sed -E -i.bak "s|(dir=).*|\1'$dir'|" file2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading