0

I have a string that is a path:

/tmp/something

I need to escape the forward slashes with backslashes:

\/tmp\/something

How can I do this? Maybe sed?

Please point me in the right direction.

3 Answers 3

4

You can do it with Bash's own variable manipulation methods (parameter expansion), though the syntax is fairly monstrous:

$ string='/tmp/something'
$ escapedstring="${string//\//\\\/}"
$ printf '%s\n' "$escapedstring"     
\/tmp\/something

To explain this further, in bash ${var//xxx/yyy} means "take variable var and replace all occurrences of xxx with yyy." In this case, you need to escape the slashes in specifying the substituend and substitute; the former is \/ for a single forward slash and latter is \\\/ for a backslash plus forward slash, so you end up with the ridiculous looking ${string//\//\\\/}.

Remember not to use echo to display its contents as depending on the implementation or environment, echo may do it's own processing of backslash characters.

1

sed is the right direction! Follow a tutorial like https://www.grymoire.com/Unix/Sed.html#uh-1 ; the very basic method is

echo $string | sed 's;old;replacement;g' 

where s is the command, i.e. "search and replace", g is the flag that means "repeat on each line until you're done", old is what you want to replace (/ in your case) and replacement is what you want to replace it with. (You might need to escape the backslash, so \\/.)

Have fun!

3
  • sed processes each line as default, g flag says: repeat on each match on a line until end of line. If not used sed stop searching on first match on a line, and skip to next line.
    – schweik
    Apr 23 at 18:55
  • @schweik exactly what a I meant with repeat on each line (should probably have used "within") Apr 23 at 18:56
  • No problem, I wrote it not to you but to any newbie :-)
    – schweik
    Apr 23 at 18:58
1

You can do something along these lines.

# let
str='/tmp/something'
str_esc=$(printf '%s\n' "$str" | sed 's:/:\\&:g')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.