プログラミング

Bash 更新日時が期間範囲内の日付時間のファイルを出力する

Linuxパソコン・サーバーのBashプログラミング言語・スクリプティング言語のコマンドラインで、更新日時が期間範囲内の日付時間のファイルを出力するコマンドの実装方法について紹介します。

以下は更新日の新しい順で10件のファイルを出力する例です。

find . -type f -printf '%Ts\t%p\n' | sort -n -r | sed -Ee 's/^.*\t//g' | head

./ShareX_ScreenShot_e55d3fd6-ba65-4230-98fe-fcea0dde5142.png
./ShareX_ScreenShot_926e9d7f-6f7e-4146-a656-aae6fcbbfe66.png
./ShareX_ScreenShot_46de4c81-9393-4472-9763-bbad1f4dc4ed.png
./ShareX_ScreenShot_6b0a27fe-9f3b-4429-a377-fd9a0877263c.gif
./ShareX_ScreenShot_2baf49f9-7742-4931-889e-3489db8f675b.png
...

ここにさらに、本日7月7日の4時から6時までが更新日時であるファイルのみを出力したい、という場合。

find . -type f -printf '%Ts\t%p\n' | sort -n -r | awk -F '\t' '$1 >= 1562439600 && $1 <= 1562446800{print $0}' | sed -Ee 's/^.*\t//g'

これは以下のようにでき、

find . -type f -printf '%Ts\t%p\n' | sort -n -r | awk -v from="1562439600" -v to="1562446800" -F '\t' '$1 >= from && $1 <= to{print $0}' | sed -Ee 's/^.*\t//g'

実用する場合は以下のようなフォーマットになります。

find . -type f -printf '%Ts\t%p\n' | sort -n -r | awk -v from="$( date --date "7/7 4:00" +%s )" -v to="$( date --date "7/7 6:00" +%s )" -F '\t' '$1 >= from && $1 <= to{print $0}' | sed -Ee 's/^.*\t//g'

関数として利用する場合は以下のような感じ。


getlastsByDate(){

    : getlastsByDate [from] [to] [dir]

    find ${3:-.} -type f -printf '%Ts\t%p\n' | sort -n -r | awk -v from="$( date --date "${1:-0:00}" +%s )" -v to="$( date --date "${2:-23:59}" +%s )" -F '\t' '$1 >= from && $1 <= to{print $0}' | sed -Ee 's/^.*\t//g'

}

実用例

以下のように6月28日のファイルが3つあるようなフォルダを例として、6月1日から月末までのファイルを削除したい、という例

yuis ASUS /mnt/c/_tmp/20190627124456$ ls
total 8
166351711236005864 drwxrwxrwx 1 yuis yuis 4096 Jul  7 05:52 ..
285134151409284381 drwxrwxrwx 1 yuis yuis 4096 Jun 28 19:41 .
144959613006035510 -rwxrwxrwx 1 yuis yuis    0 Jun 28 19:41 tmp.html is DszR7hzC5AUm9ZG6OMcmjsT9CpBvwyGm.html.is.tag
118500965195223995 -rwxrwxrwx 1 yuis yuis 3675 Jun 28 19:41 tmp.html
 15762598696119839 -rwxrwxrwx 1 yuis yuis 3675 Jun 28 19:40 DszR7hzC5AUm9ZG6OMcmjsT9CpBvwyGm.html

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_9a900a3f-865f-4b38-b933-16d2c4d1ee99.png

以下で指定期間のファイルの取得ができる。

yuis ASUS /mnt/c/_tmp/20190627124456$ getlastsByDate 6/1 7/1 .
./tmp.html is DszR7hzC5AUm9ZG6OMcmjsT9CpBvwyGm.html.is.tag
./tmp.html
./DszR7hzC5AUm9ZG6OMcmjsT9CpBvwyGm.html

そして削除。

rm "$( getlastsByDate 6/1 7/1 . )"

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です