
我有一個包含 1000 個(或更多)文件的資料夾。我想要一個腳本來建立一個編號資料夾,然後將前 20 個檔案(按名稱排序)移到該資料夾中。然後應該對其他檔案執行此操作,將資料夾編號增加 1,直到所有檔案都在資料夾中。
我已嘗試以下命令,但它不會自動執行整個目錄,也不會自動增加資料夾編號:
N=1000;
for i in ${srcdir}/*; do
[ $((N--)) = 0 ] && break
cp -t "${dstdir}" -- "$i"
done
如何使用 bash 來完成此操作?
答案1
此腳本採用兩個(可選)參數:要分區的目錄和分區大小。由於您沒有說您是否只想移動文件,或移動所有內容,我假設您指的是文件,所以我使用了 find 命令。
一些評論,
- 如果您沒有指定 shell,那麼在 perl、ruby 或 python 中更容易完成類似的操作。
- find with maxdepth 1 只找目錄
- 您可以將檔案移動到任何位置,只需更改資料夾命名即可
- 由於使用了find,因此可以添加-name、-mtime、-ctime等。
複製一些.sh,
#!/bin/bash
path=${1:-"."} #directory to start
howmany=${2:-20} #partition size
pushd $path; #move there
part=1; #starting partition
LIST="/usr/bin/find -maxdepth 1 -type f" #move only files?
#LIST="ls" #move everything #be careful, $folder will get moved also :-)
count=`$LIST |/usr/bin/wc -l`; #count of files to move
while [ $count -gt 0 ]; do
folder="folder-$part";
if [ ! -d $folder ]; then /usr/bin/mkdir -p $folder; fi
/usr/bin/mv `$LIST |/usr/bin/sort |/usr/bin/head -$howmany` $folder/.
count=`$LIST |/usr/bin/wc -l`; #are there more files?
part=$(expr $part + 1)
done
popd $path
這是一個用於測試的腳本(我沒有多餘的 1000 個檔案),
for f in 0 1 2 3 4 5 6 7 8 9; do
for g in 0 1 2 3 4 5 6 7 8 9; do
for h in 0 1 2 3 4 5 6 7 8 9; do
touch $f$g$h
done
done
done
答案2
當for
你的 filesName 以對應的數字結尾但 shell 是zsh
.
for N in {0..800..20}: do
mkdir "dir$N"
mv "files{$N..$((N+19))}" "/path/to/dir$N/"
done
如果它在 中bash
,那麼:
for N in {0..800..20}: do
mkdir "dir$N"
eval mv "files{$N..$((N+19))}" "/path/to/dir$N/"
done