Bash string replace "with" \ "for the file path - variable extension

I know that there is a better way to do this.

  • What is the best way?

  • How do you replace a string in a string variable in bash?

Example: (using php because I know)

$path = "path/to/directory/foo bar";

$path = str_replace(" ", "\ ", "$path");

echo $path;

returns:

path/to/directory/foo\ bar
+5
source share
2 answers

To perform a specific replacement in bash:

path='path/to/directory/foo bar'
echo "${path// /\\ }"
  • Do not use the prefix $when assigning variables to bash.
  • There =should be no spaces around .
  • , path , - : bash , ( ) ; ( , , - , )

"${path///\\ }":

  • , {...}
  • // , ( / ).
  • / , ( ) \\.
  • \, \\, \ escape-. , , .

, bash ( ) , [ ] . , , , ,... - . BashGuide .

, :

  • , (, *.txt); , v='dear me'; echo "${v/m*/you}" v='dear me'; echo "${v/m*/you}" 'dear you'. , .
    • , :
      • /, , - .
      • #
      • %
  • - , ; , , , , , $(...) ,...; :
    • v='sweet home'; echo "${v/home/$HOME}" v='sweet home'; echo "${v/home/$HOME}", , 'sweet/home/jdoe'.
    • v='It is now %T'; echo "${v/\%T/$(date +%T)}" v='It is now %T'; echo "${v/\%T/$(date +%T)}" It is now 10:05:17, , It is now 10:05:17.
    • o1=1 o2=3 v="$o1 + $o2 equals result"; echo "${v/result/$(( $o1 + $o2 ))}" o1=1 o2=3 v="$o1 + $o2 equals result"; echo "${v/result/$(( $o1 + $o2 ))}" '1 + 3 equals 4' ( )

- .

+12

sed? , ?

#!/bin/bash

path="path/to/directory/foo bar"
new_path=$(echo "$path" | sed 's/ /\\ /g')
echo "New Path: '$new_path"

@n0rd , , , ; - ...

path="path/to/directory/foo bar"
echo "test" > "$path"
+3

Source: https://habr.com/ru/post/1535649/


All Articles