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 to Replace a string with variable

I have a data in variable which I need to replace a string in file with.

  app_name="Test 12 & - 3"
  echo "application_name" > test.txt
  sed  "s/application_name/$app_name/g" test.xt

I get following as output

Test 12 application_name - 3

instead of

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

Test 12 & - 3

The same command works fine if the var doesn’t have & but with & it doesnt work.

Any suggestions ?

Regards.

>Solution :

& in the substitution part of the s command has a special meaning in sed (and in other search and substitute facilities, such as Vim’s): it is substituted with the string that matched the search pattern, which in your case is the application_name string between the first two /s.

To include a literal &, you need to escape it when it appears in between the second and third /s of the sed command:

sed "s/application_name/${app_name/&/\\&}/g" test.txt

The ${app_name/&/\\&} part is nothing else than ${app_name} with & substituted by \& (since \ itself is a special character, I had to escape it too, \\&). See also man bash for more details (search for Pattern substitution in there).

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