18

I've got 291 numbered files (starting at 001 - title and ending at 291 - title) that need moved into separate directories. (001 to 021 to folder 1, 022 to 053 to folder 2, they aren't necessarily the same number of files each time).

I figured I could do it in a yucky way like this: ls | head -n 21 | sed -r 's|(.*)|mv \1 /path/to/folder1|' | sh

I'm almost positive there's a better way, so what would it be?

EDIT: So that would've worked fine, but I remembered...

I'm not stuck using a terminal, so I used a file manager to click and drag. Question still stands though.

Rob
  • 2,422

3 Answers3

32

Since you said it's not always exactly 21 files than you need to move the files manually, and to do that effectively you could use brace expansion:

mv filename{001..21} dir1
mv filename{022..53} dir2
...
drrlvn
  • 6,713
1

This will move the files as you described (except that the second range would be 022 to 042 for the second 21 files).

for ((i = 1; i <= 291; i++))
do
    ((d = (i - 1) / 21 + 1))
    printf -v file 'filename%03d' "$i"
    printf -v dir  'dirname%02d'  "$d"
    [[ -d "$d" ]] && mkdir "$d"
    mv "$f" "$d"
done
1

What I mean is to move a lot of files(like ten thousands or a million), shell will complain about the file list too long if you just use {1..20}, so

In zsh, you can load the mv builtin:

setopt extended_glob zmodload

zsh/files

after doing that, you can use command like:

mv ./somefolder/{1..100000}.txt  pathto/yourfolder/

or if you are writing some shell scripts, you can do something like this:

for i in `seq $start $end`;  
    do  mv "prefix${i}suffix.txt" pathto/yourfolder/  
done

if you are not using zsh, you may refer to https://unix.stackexchange.com/questions/128559/solving-mv-argument-list-too-long

Arron Cao
  • 111