Home > Net >  sed and special characters inside a variable (macOS Monterey)
sed and special characters inside a variable (macOS Monterey)

Time:06-25

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:

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?

CodePudding user response:

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.

CodePudding user response:

Nobody ever remembers that sed has commands besides s. It also has, for example, c to change a matching line:

sed -i '' '/"PATH_VAR=.*"/c\
"PATH_VAR='"$PATH_VAR"'"
' file.txt

Your variable just needs to not have any newlines in it with this approach.

  • Related