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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityI 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.
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.
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!
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.
You can do something along these lines.
# let
str='/tmp/something'
str_esc=$(printf '%s\n' "$str" | sed 's:/:\\&:g')