Create directory using filenames and move the files to its repective folder

directoryfilesrename

I have a folder with around 150 text files. I would like to create folders in the name of the 150 files. After that I would like the text file to be moved to its respective folder.

Example names of the files inside myfolder directory:

~/myfolder/
       |______ ajhaslf.txt
       |______ oiueed.txt
       |______ dsflije.txt

How I would like my new structure to be:

~/myfolder/
       |______ ajhaslf
                   |____ajhaslf.txt
       |______ oiueed
                   |____oiueed.txt
       |______ dsflije
                   |____dsflije.txt

Of course creating directory with the filenames is not a problem for me with mkdir.

Best Answer

@gniourf_gniourf has the right idea:

set -o errexit -o nounset
cd ~/myfolder
for file in *.txt
do
    dir="${file%.txt}"
    mkdir -- "$dir"
    mv -- "$file" "$dir"
done

This should be POSIX compliant. It is not re-entrant. It will not work if you have any two files named something.txt and something.txt.txt.

Related Question