年に基づいてファイルを移動する方法

年に基づいてファイルを移動する方法

年に基づいてファイルを移動する必要があります。次のfindコマンドを使用しました

find /media/WD/backup/osool/olddata/ -mtime +470 -exec ls -lrth {} \;|sort -k6

しかし、このコマンドを正常に実行するには、正確な数字を知る必要がありますmtime。現時点では 470 は単なる推測です。つまり、2012 年を指定できれば、2012 年に関連するファイルのみが返されます。

だから私はどうしたらいいかアドバイスが欲しい

年(例:2012)に基づいてファイルを検索し、他のディレクトリに移動します。

OS release 5.2

FIND version
GNU find version 4.2.27
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION SELINUX 

答え1

-newermtこのオプションを使用する理由find:

find /media/WD/backup/osool/olddata/ -newermt 20120101 -not -newermt 20130101

2012 年に変更されたすべてのファイルを取得します。

検索がサポートされていない場合は、-newermtオフセット計算の使用を防ぐために次の操作を行うこともできます。

touch -d 20120101 /var/tmp/2012.ref
touch -d 20130101 /var/tmp/2013.ref
find /media/WD/backup/osool/olddata/ -newer /var/tmp/2012.ref -not -newer /var/tmp/2013.ref

マンページ

-newerXY reference
          Compares the timestamp of the current file with reference.   The
          reference  argument  is  normally the name of a file (and one of
          its timestamps is used for the comparison) but it may also be  a
          string  describing  an  absolute time.  X and Y are placeholders
          for other letters, and these letters select which time belonging
          to how reference is used for the comparison.

          ...

          m   The modification time of the file reference
          t   reference is interpreted directly as a time

答え2

touch --date=2011-12-31T23:59:59 start
touch --date=2012-12-31T23:59:59 stop
find / -newer start \! -newer stop -printf %Tx" "%p\\n

-exec ls意味が分かりません。

答え3

マニュアルページによると、-mtime の引数は検索する日数です。これを使用して、date +%j現在の年の 1 月 1 日からの日数を調べることができます。

答え4

作業ディレクトリからこれを行う場合は、代わりに次のように実行できます。

ls -l |awk '{ if ($8 == "2013") print $9 }'

これにより、処理が大幅に簡素化され、重複も発生しません。ただし、これらのファイルは 6 か月以上前のものであると想定されるため、ls正確な時刻ではなく年が印刷されます。

6 か月以上前のファイルの場合は、次のように置き換える必要があります。

ls -l |awk '{ if ($6 == "May") print $9 }' 

または、月に応じて同様のものになります。ファイルを移動する月のリストを作成する場合 (または年のリストを作成する場合) は、次のようにします。

month="May Jun Jul"; 
for i in `echo $month`; 
do 
    for j in `ls -l |awk '{ if ($6 == "'$i'") print $9}'`
    do
        mkdir -p $i
        mv $j $i
    done
done

関連情報