How can I add a backslash before all spaces?

Solution 1:

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

  1. sed

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

    or

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

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

    or

    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// /\\ }
    

Solution 2:

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

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