I am new to shell script. Can someone help me with command to escape the space with \"\\ \".
I have a variable FILE_PATH=/path/to my/text file ,
I want to escape the spa
Use quotes to preserve the SPACE character
tr is used only for replacing individual characters 1 for 1. Seems to be that you need sed.
echo $FILE_PATH | sed -e 's/ /\\ /'
seems to do what you want.
You can use 'single quotes' to operate on a path that contains spaces:
cp '/path/with spaces/file.txt' '/another/spacey path/dir'
grep foo '/my/super spacey/path with spaces/folder/*'
in a script:
#!/bin/bash
spacey_dir='My Documents'
spacey_file='Hello World.txt'
mkdir '$spacey_dir'
touch '${spacey_dir}/${spacey_file}'
If you are using bash, you can use its builtin printf's %q formatter (type help printf
in bash):
FILENAME=$(printf %q "$FILENAME")
This will not only quote space, but also all special characters for shell.
FILE_PATH=/path/to my/text file
FILE_PATH=echo FILE_PATH | tr -s " " "\\ "
That second line needs to be
FILE_PATH=echo $FILE_PATH | tr -s " " "\\ "
but I don't think it matters. Once you have reached this stage, you are too late. The variable has been set, and either the spaces are escaped or the variable is incorrect.
FILE_PATH='/path/to my/text file'
Do not forget to use eval when using printf guarding.
Here's a sample from Codegen Script under Build Phases of Xcode (somehow PROJECT_DIR is not guarded of spaces, so build was failing if you have a path with spaces):
PROJECT_DIR_GUARDED=$(printf %q "$PROJECT_DIR")
eval $PROJECT_DIR_GUARDED/scripts/code_gen.sh $PROJECT_DIR_GUARDED
You can do it with sed
:
NEW_FILE_PATH="$(echo $FILE_PATH | sed 's/ /\\ /g')"