linux環境でディレクトリ配下の最新更新ファイルを把握したい

タイトル通りでして、ディレクトリ配下(サブディレクトリ配下含む)のファイルの中から、最新の更新ファイルを調べる必要が出てきました。

カレントから調べるならlsとsortを繋いで終了なのですが、サブディレクトリも調べるとなると少々厄介。
この程度の処理にシェルスクリプト書くのも面倒なので、一撃で終えられるようコマンド繋げましたのでそのメモ。

結論

find ./ -type f -print0 | xargs --null -i ls -l --time-style=long-iso "{}" | sort -k 6,7 | tail -1

以上。これで最新の更新ファイルが一個だけ出力されるはず。
お行儀の良い所ならもうちょいシンプルに以下でも可。

find ./ -type f | xargs ls -l --time-style=long-iso | sort -k 6,7 | tail -1

何をしているのか

find ./ -type f

findコマンドでカレント以下からファイル形式のものだけを検索。

find ./ -type f | xargs ls -l

findで引っ掛けたファイル一覧をlsコマンドでタイムスタンプ出力。

find ./ -type f | xargs ls -l --time-style=long-iso

そのままだとソートに不便なので、日付の形式を変更。

find ./ -type f | xargs ls -l --time-style=long-iso | sort -k 6,7

年月日と時刻でソート。

find ./ -type f | xargs ls -l --time-style=long-iso | sort -k 6,7 | tail -1

最新のファイルのみを表示。

find ./ -type f -print0 | xargs --null -i ls -l --time-style=long-iso "{}" | sort -k 6,7 | tail -1

findとxargsの区切り文字をnull文字にし、lsコマンドで扱えるようにする。

参考サイト
http://takuya-1st.hatenablog.jp/entry/2014/05/07/014251
http://sea-otter-factory.blogspot.jp/2008/07/unix-xargs.html

コメントを残す