How can I put a backslash before every space, preferably by using tr or sed commands?

Here is my script:

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:


Expected output:

hello\ bye
  • Could you please elaborate a bit on that? Are you looking for a script that changes a text file? What exactly are you looking for?
    – Fabby
    Mar 14 '15 at 18:14
  • tr x ' ', where x is the character you want to replace?
    – Doorknob
    Mar 14 '15 at 18:16
  • updated - added example.
    – daka
    Mar 14 '15 at 19:20

tr can't do multiple characters. Use one of these instead:

  1. sed

    echo "$line" | sed 's/ /\\ /g' 


    sed 's/ /\\ /g' <<< "$line"
  2. Perl

    echo "$line" | perl -pe 's/ /\\ /g'  


    perl -pe 's/ /\\ /g'<<< "$line"

    Perl also has a nifty function called quotemeta which can escape all odd things in a string:

    line='@!#$%^&*() _+"'
    perl -ne 'print quotemeta($_)' <<< $line

    The above will print

    \@\!\#\$\%\^\&\*\(\)\ _\+\"\
  3. You can also use printf and %q:

    %q  quote the argument in a way that can be reused as shell input

    So, you could do

    echo "$line" | printf "%q\n" 

    Note that this, like Perl's quotemeta will escape all special characters, not just spaces.

    printf "%q\n" <<<$line
  4. If you have the line in a variable, you could just do it directly in bash:

    echo ${line// /\\ }
  • yes this works, but does not work when wanting to replace all occurences of "a" with a backlash+space.
    – daka
    Mar 14 '15 at 19:22
  • @sudoman I added some more options since you have the line in a variable already.
    – terdon
    Mar 14 '15 at 20:04
  • Bash's printf builtin has functionality similar to quotemeta -- printf '%q\n' "$line" should do it IIRC.
    – evilsoup
    Mar 15 '15 at 19:19

There is AWK missing in the list of all the possible solutions :)

$ echo "Hello World" | awk '{gsub(/ /,"\\ ");print}'                                                                             
Hello\ World

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.