How can I put a backslash before every space, preferably by using tr
or sed
commands?
Here is my script:
#!/bin/bash
line="hello bye"
echo $line | tr ' ' "\\\ "
This is supposed to replace spaces with a backslash followed by a space, but it's only replacing the spaces with a backslash and not backlash+space.
This is the output I get:
hello\bye
Expected output:
hello\ bye
Best Answer
tr
can't do multiple characters. Use one of these instead:sed
or
Perl
or
Perl also has a nifty function called
quotemeta
which can escape all odd things in a string:The above will print
You can also use
printf
and%q
:So, you could do
Note that this, like Perl's
quotemeta
will escape all special characters, not just spaces.If you have the line in a variable, you could just do it directly in bash: