Unix command to escape spaces

后端 未结 7 1349
春和景丽
春和景丽 2020-12-14 07:21

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

相关标签:
7条回答
  • 2020-12-14 07:44

    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.

    0 讨论(0)
  • 2020-12-14 07:48

    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}'
    
    0 讨论(0)
  • 2020-12-14 07:50

    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.

    0 讨论(0)
  • 2020-12-14 07:56
    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'

    0 讨论(0)
  • 2020-12-14 08:01

    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
    
    0 讨论(0)
  • 2020-12-14 08:03

    You can do it with sed :

    NEW_FILE_PATH="$(echo $FILE_PATH | sed 's/ /\\ /g')"
    
    0 讨论(0)
提交回复
热议问题