altralaser
altralaser

Reputation: 2073

Find files with spaces in the bash

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.

Upvotes: 17

Views: 34865

Answers (3)

Liran H
Liran H

Reputation: 10609

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 "/")

Upvotes: 0

Rakesh Gupta
Rakesh Gupta

Reputation: 3780

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

Upvotes: 28

beliy
beliy

Reputation: 445

With find:

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

Upvotes: 10

Related Questions