Lolly
Lolly

Reputation: 36422

Unix command to escape spaces

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 spaces alone FILE_PATH=/path/to\ my/text\ file

I tried with tr -s command but it doesnt help

FILE_PATH=echo FILE_PATH | tr -s " " "\\ "

Can somebody suggest the right command !!

Upvotes: 40

Views: 121162

Answers (7)

Gilles Quénot
Gilles Quénot

Reputation: 185161

You can do it with sed :

NEW_FILE_PATH="$(echo $FILE_PATH | sed 's/ /\\\ /g')"

Upvotes: 2

kikiwora
kikiwora

Reputation: 1784

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

Upvotes: 1

sureshvv
sureshvv

Reputation: 4422

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.

Upvotes: 2

jahroy
jahroy

Reputation: 22692

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}'

Upvotes: 9

Bao Haojun
Bao Haojun

Reputation: 1006

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.

Upvotes: 66

hymie
hymie

Reputation: 2058

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'

Upvotes: -4

William Pursell
William Pursell

Reputation: 212248

There's more to making a string safe than just escaping spaces, but you can escape the spaces with:

FILE_PATH=$( echo "$FILE_PATH" | sed 's/ /\\ /g' )

Upvotes: 13

Related Questions