1

I have a directory of 150 files that I wanted split into sub-directories of 25 files each: 1-25 into dir1, 26-50 into dir2, and so on. How can I accomplish this?

dir1/fre_4_g2_c3654214.h3

dir1/fre_4_g2_c0585433.h3

dir1/fre_4_g2_c3565415.h3

... and so on

and what I'd want to do is

dir1/fre_4_g2_c3654214.h3

dir2/fre_4_g2_c0585433.h3

dir3/fre_4_g2_c3565415.h3
MelBurslan
  • 6,836
  • 2
  • 24
  • 35
e1v1s
  • 161
  • 4
  • You should tell us what you already tried! – Lucas May 16 '16 at 20:21
  • I looked at this post: http://unix.stackexchange.com/questions/228494/how-to-split-a-directory-of-files-into-sub-directories but was unable to figure out how to use it for what I'm doing. Specifically, I tried for f in *.dat; do mkdir -p "${f:5:2}"; mv "$f" "${f:5:2}/"; done and got 1 directory with 4 files and another with over 100 – e1v1s May 16 '16 at 20:22
  • Add some examples of your file names? Are they all similarly named? Do they have file extensions of some sort? etc – Grimdari May 16 '16 at 20:25
  • Yes, they're all similarly named and have the same extension – e1v1s May 16 '16 at 20:26
  • notice how in the first 3 lines that the parent directory is dir1 and the bottom 3 examples the parent directory is different for each file? – e1v1s May 16 '16 at 20:35
  • Do your 150 files need to be partitioned into specific groups, or is it just any 25 per subdirectory? – roaima May 16 '16 at 22:25

1 Answers1

1

This will sort the files alphanumerically and move the first 25 files into subdirectory dir0, the next 25 into dir1, etc., until all files are moved:

 n=0; for f in *; do d="dir$((n++ / 25))"; mkdir -p "$d"; mv -- "$f" "$d/$f"; done

For those who prefer their commands spread over multiple lines:

n=0
for f in *
do
    d="dir$((n++ / 25))"
    mkdir -p "$d"
    mv -- "$f" "$d/$f"
done

This will work under either ksh or bash.

don_crissti
  • 79,330
  • 30
  • 216
  • 245
John1024
  • 73,527
  • 11
  • 167
  • 163