在循环中创建目录并将文件移动到这些目录

Pol*_*Ice 5 command-line shell-script rename files

考虑一个包含 N 个文件的目录。

我可以按字母顺序列出文件并按以下方式存储列表

ls > list
Run Code Online (Sandbox Code Playgroud)

然后我想在同一目录中创建n个子目录,可以通过以下方式完成

mkdir direc{1..n}
Run Code Online (Sandbox Code Playgroud)

现在我想将前 m 或前 5 (1-5) 个文件从 移动listdirec1,接下来的 5 个文件即 6-10 移动到 ,direc2依此类推。

这对你们来说可能是一项微不足道的任务,但目前我无法做到。请帮忙。

gle*_*man 3

list=(*)     # an array containing all the current file and subdir names
nd=5         # number of new directories to create
((nf = (${#list[@]} / nd) + 1))  # number of files to move to each dir
                                 # add 1 to deal with shell's integer arithmetic

# brace expansion doesn't work with variables due to order of expansions
echo mkdir $(printf "direc%d " $(seq $nd))

# move the files in chunks
# this is an exercise in arithmetic to get the right indices into the array
for (( i=1; i<=nd; i++ )); do
    echo mv "${list[@]:(i-1)*nf:nf}" "direc$i"
done
Run Code Online (Sandbox Code Playgroud)

测试后删除两个“echo”命令。

或者,如果您想每个目录包含固定数量的文件,这更简单:

list=(*)
nf=10
for ((d=1, i=0; i < ${#list[@]}; d++, i+=nf)); do
    echo mkdir "direc$d"
    echo mv "${list[@]:i:nf}" "direc$d"
done
Run Code Online (Sandbox Code Playgroud)