1000個のファイルを含むフォルダから20個のファイルの配置を番号付きフォルダに繰り返し移動する方法

1000個のファイルを含むフォルダから20個のファイルの配置を番号付きフォルダに繰り返し移動する方法

1000を超えるファイルを含むフォルダがあります。番号付きフォルダを作成し、最初の20ファイル(名前でソート)をそのフォルダに移動するスクリプトが必要です。その後、他のファイルに対してこれを行う必要があり、すべてのファイルがフォルダに含まれるまでフォルダ番号を1ずつ増やす必要があります。

次のコマンドを試しましたが、ディレクトリ全体を自動的に実行せず、フォルダ番号を自動的に増やすこともありません。

N=1000;
for i in ${srcdir}/*; do
  [ $((N--)) = 0 ] && break
  cp -t "${dstdir}" -- "$i"
done

Bashを使ってこれを行うにはどうすればよいですか?

ベストアンサー1

スクリプトは、分割するディレクトリとパーティションサイズという2つの(オプション)パラメータを使用します。私はファイルだけを移動するのか、それともすべてを移動するのか言わなかったので、ファイルを意味すると仮定してfindコマンドを使用しました。

コメント、

  • シェルを指定しないと、Perl、Ruby、またはPythonで同様の操作を実行する方が簡単です。
  • maxlength 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

おすすめ記事