17

I want to search for files in a folder which have a space in its filenames, f.e.

/vol1/apache2/application/current/Test 1.pdf /vol1/apache2/application/current/Test 2.pdf 

I know there's a find command but I can't figure out the correct parameters to list all those files.

3
  • 6
    How about ls *" "*? find . -name "* *"? Commented May 18, 2017 at 14:33
  • 1
    echo *" "* also works Commented May 18, 2017 at 14:36
  • Sorry I forgot to say: I need the file list for a given folder and all subfolders (recursive search)... Commented May 18, 2017 at 14:52

3 Answers 3

29

Use find command with a space between two wildcards. It will match files with single or multiple spaces. "find ." will find all files in current folder and all the sub-folders. "-type f" will only look for files and not folders.

find . -type f -name "* *" 

EDIT

To replace the spaces with underscores, try this

find . -type f -name "* *" | while read file; do mv "$file" ${file// /_}; done 
Sign up to request clarification or add additional context in comments.

5 Comments

And is there also a possibility to rename the results and automatically remove the spaces?
I think better use xargs than while in this case.
This will fail if one parent directory contains spaces in its name
This is good when parent dir doesn't have spaces
This is a nice approach. First rename the files and then do the operations
10

With find:

find "/vol1/apache2/application/current" -type f -name "*[[:space:]]*" 

2 Comments

Nice! Can I add more characters or exclude filename extensions?
@ssavva05 yeap Examples: add characters - find "/vol1/apache2/application/current" -type f -name "*Test[[:space:]]*.pdf" exclude extensions - find "/vol1/apache2/application/current" -type f -name "*[[:space:]]*" -not -name "*.txt"
0

The following worked for me to find all files containing spaces:

find ./ -type f | grep " " 

To also rename all found files to the same filename without the spaces, run the following:

find ./ -type f | grep " " | while read file; do mv "$file" ${file// }; done 

Ways to configure the above script:

  • To rename only directories, change -type f to -type d
  • To use git-aware rename, change do mv to do git mv
  • To rename differently, change ${file// }; to ${file// /[some-string]};. For example, to replace the spaces with "_", use: ${file// /_}; (notice the leading "/")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.