Bash – Create Directories from List of Files with Spaces

bashfilesrhel

I have a directory with a list of files in it. All these files have spaces in their names.

I would like to create a directory, for each file, with the name of the file except the extension (which is .doc for all of them).

E.g.:

My directory content

first file.doc 
second file.doc 
third file.doc

Expected result

first file/first file.doc 
second file/second file.doc
third file/third file.doc

I have this command to know the directory name I have to create:

find . -maxdepth 1 -name "*.doc" | awk -F ".doc" '{print $1}'

With this, the result is:

first file
second file
third file

I know need to create a directory per entry.

I've tried the following with no success:

find . -maxdepth 1 -name "*.doc" | awk -F ".doc" '{print $1}' -exec mkdir '{}' \;
#error with awk: it cannot open the file -exec because it does not exist

mkdir `find . -maxdepth 1 -name "*.doc" | awk -F ".doc" '{print $1}'`
#it creates several directories per name because there are spaces in the names

mkdir `"find . -maxdepth 1 -name "*.doc" | awk -F ".doc" '{print $1}'"`
#-bash: find . -maxdepth 1 -name *.doc | awk -F .doc '{print }': command not found

mkdir "`find . -maxdepth 1 -name "*.doc" | awk -F ".doc" '{print $1}'`"
#it tries to create a unique directory with all the file names as a single name, which is not good of course

If I could, I would just remove all the spaces in the file names, but I need to keep them for project constraints :/

Once I can create these directories, I will have to figure out how to move all the files in their matching directories.
It all can be done in a single command, I'll take it 🙂

I'm using bash and RedHat 2.6.

Thanks for your help.
Laurent

Best Answer

Spaces in a file/directory name are fine as long as those names are properly quoted:

find . -maxdepth 1 -name "*.doc" | while IFS= read -r f; do 
    mkdir -- "${f%.doc}"; 
done
Related Question