Shell-Script

循環創建目錄並將文件移動到這些目錄

  • March 15, 2015

考慮一個包含 N 個文件的目錄。

我可以按字母順序列出文件並儲存列表

ls > list

然後我想在同一目錄中創建 n 個子目錄,可以通過

mkdir direc{1..n}

現在我想移動第一個 m 或者說前 5 (1-5) 個文件從listto direc1,下一個 5 文件即 6-10 todirec2等等。

這對你們來說可能是一項微不足道的任務,但目前我無法做到。請幫忙。

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

測試後刪除兩個“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

引用自:https://unix.stackexchange.com/questions/189815