-1

I would like to escape a file path that is stored in a variable in a bash script. I read several threads about escaping back ticks or but it seems not working as it should:

I have this variable: The variables value is entered during the bash script execution as user parameter

CONFIG="/home/teams/blabla/blabla.yaml"

I would need to change this to: \/home\/teams\/blabla\/blabla.yaml

How can I do that with in the script via sed or so (not manually)?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
FotisK
  • 1,055
  • 2
  • 13
  • 28
  • I'm not quite sure what the question is but you can do something like that I believe: ```\/home\/teams\/blabla\/blabla.yaml```, escaping the / sign – Bogdan Stoica Oct 13 '21 at 13:04

4 Answers4

2

With GNU bash and its Parameter Expansion:

echo "${CONFIG//\//\\/}"

Output:

\/home\/teams\/blabla\/blabla.yaml
Cyrus
  • 84,225
  • 14
  • 89
  • 153
1

Using the solution from this question, in your case it will look like this:

CONFIG=$(echo "/home/teams/blabla/blabla.yaml" | sed -e 's/[]\/$*.^[]/\\&/g')
Taras Khalymon
  • 614
  • 4
  • 11
0
echo "/home/teams/blabla/blabla.yaml" | sed 's/\//\\\//g'
\/home\/teams\/blabla\/blabla.yaml

explanation:

backslash is used to set the following letter/symbol as an regular expression or vice versa. double backslash is used when you need a backslash as letter.

Mario
  • 679
  • 6
  • 10
0

Why does that need escaping? Is this an XY Problem?

If the issue is that you are trying to use that variable in a substitution regex, then the examples given should work, but you might benefit by removing some of the "leaning toothpick syndrom", which many tools can do just by using a different match delimiter. sed, for example:

$: sed "s,SOME_PLACEHOLDER_VALUE,$CONFIG," <<< SOME_PLACEHOLDER_VALUE
/home/teams/blabla/blabla.yaml

Be very careful about this, though. Commas are perfectly valid characters in a filename, as are almost anything but NULLs. Know your data.

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36