Unix command to exit space

I am new to shell script. Can someone help me with a team to avoid a space using "\". I have a FILE_PATH = / path / variable in my / text file,
I want to just avoid FILE_PATH spaces = / path / to \ my / text \ file

I tried the tr -s command but it doesn’t help

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

Can someone suggest the right team!

+21
linux unix shell
09 Oct '12 at 19:25
source share
6 answers

If you use bash, you can use the built-in printf% q formatter (type help printf in bash):

 FILENAME=$(printf %q "$FILENAME") 

This will not only quote the space, but all special characters for the shell.

+32
Oct 10 '12 at 2:14
source share

There is more to making a string safe than just escaping spaces, but you can avoid spaces with:

 FILE_PATH=$( echo "$FILE_PATH" | sed 's/ /\\ /g' ) 
+10
Oct 09 '12 at 19:28
source share

You can use "single quotes" to work along 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 script:

 #!/bin/bash spacey_dir='My Documents' spacey_file='Hello World.txt' mkdir '$spacey_dir' touch '${spacey_dir}/${spacey_file}' 
+7
Oct 10
source share

Use quotation marks to preserve the space character

tr is only used to replace individual 1 characters with 1. It seems like you need sed.

 echo $FILE_PATH | sed -e 's/ /\\ /' 

It seems to do what you want.

+2
Oct 10
source share

You can do this with sed :

 NEW_FILE_PATH="$(echo $FILE_PATH | sed 's/ /\\ /g')" 
+1
Oct 09 '12 at 19:28
source share
 FILE_PATH=/path/to my/text file FILE_PATH=echo FILE_PATH | tr -s " " "\\ " 

This second line should be

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

but I don’t think it matters. Once you have reached this stage, you are late. The variable has been set and spaces are escaped or the variable is incorrect.

FILE_PATH = '/ path / to my / text file

-3
09 Oct '12 at 19:29
source share



All Articles