5

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.

  • 1
    cd into your folder and: for file in *.txt; do mkdir -- "${file%.txt}"; mv -- "$file" "${file%.txt}"; done – gniourf_gniourf Jun 27 '14 at 12:01
  • mkdir: cannot create directory ‘GmZzz3StdPk.txt’: File exists – biobudhan Jun 27 '14 at 12:05
  • Are you sure you copied the line I gave (especially the "${file%.txt}"? What is your shell? – gniourf_gniourf Jun 27 '14 at 12:08
  • @gniourf_gniourf: Yes, I copied the same thing and tried. My shell is bash – biobudhan Jun 27 '14 at 12:14
  • 1
    Do you have a file named GmZzz3StdPk.txt.txt? – gniourf_gniourf Jun 27 '14 at 12:18
7

@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.

  • 1
    Maybe mkdir -- "$dir" && mv -- "$file" "$dir" to make sure we don't execute uncontrolled commands. Otherwise it's perfect. :D. Not sure though about the something.txt.txt thing; that was my first thought but now I believe that something.txt would come before something.txt.txt in the expansion of *.txt. – gniourf_gniourf Jun 27 '14 at 12:26
  • @gniourf_gniourf errexit to the rescue. For the duplicate suffix, cannot create directory GmZzz3StdPk.txt definitely means that it fails when processing GmZzz3StdPk.txt.txt, independently of the files' sequence in the output. – l0b0 Jun 27 '14 at 12:29
  • And how about shopt -s nullglob too, to be sure we're on the safe side? :D. – gniourf_gniourf Jun 27 '14 at 12:30
  • That depends on whether there being no matching files is an error or not. – l0b0 Jun 27 '14 at 12:31
  • So then shopt -s failglob? – gniourf_gniourf Jun 27 '14 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.