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 and special characters inside a variable (macOS Monterey)

I’m new to shell scripting and Terminal usage.
I have the follow line of code in a zsh script, where the PATH_VAR is always an absolute folder path that I have to insert:

#!/bin/zsh
...
read PATH_VAR
sed -i '' 's/"PATH_VAR=.*"/"PATH_VAR=$PATH_VAR"/' file.txt
...

The idea is to replace the variable value on a text file, where the string I want to replace is ("" included):

"PATH_VAR=/Path/to/folder"

I set the variable as, for example, /Path/to/folder; the follow line pops out:

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

sed: line: "s/"PATH_VAR=.*"/"P ...": bad flag in substitute command: 'P'

I understand that this is due to the / that gets interpreted differently by sed; in fact when I run:

sed -i '' 's/"PATH_VAR=.*"/"PATH_VAR=\/Path\/to\/folder"/' file.txt

everything goes smoothly and the string gets replaced.
I want to know if there’s a workaround. Since the PATH_VAR is always an absolute path, I thought about recoursively adding the \ before every / that is found in the PATH_VAR variable. Is this possible with sed?

>Solution :

Instead of struggling to escape those slashes, you may want to pick another separator for sed’s s command. E.g. sed 's@....@...@' or sed 's#...#...#'

But of course, this only works if the picked separator doesn’t appear in your pattern/replacement.

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