12

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.

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

1 Answer 1

11

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

8
  • 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. Commented Jun 27, 2014 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. Commented Jun 27, 2014 at 12:29
  • And how about shopt -s nullglob too, to be sure we're on the safe side? :D. Commented Jun 27, 2014 at 12:30
  • That depends on whether there being no matching files is an error or not. Commented Jun 27, 2014 at 12:31
  • So then shopt -s failglob? Commented Jun 27, 2014 at 12:32

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.