如何根據年份移動文件

如何根據年份移動文件

我需要根據年份移動文件。我使用了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

相關內容