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
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).