LoginSignup
3
3

More than 5 years have passed since last update.

findで最新ファイルを除外する

Posted at

いまひとつスマートな書き方が思いつかなかったが、やや無理矢理ながらタイトル通りの振る舞いが出来そうなのでメモ。
「-print0 | xargs -0r ls -l」を「-delete」に置き換えて「最新ファイル以外削除」として使用する目的。

# ファイル名が不定の場合
find <path> -type f ! -path $(find <path> -type f -print0 | xargs -0r ls -tr | head -1) -print0 | xargs -0r ls -l

# ファイル名に日付が付与される場合
find <path> -type f ! -path $(find <path> -type f -print0 | xargs -0r ls -1 | sort -r | head -1) -print0 | xargs -0r ls -l

実行例

[test@test tmp]$ ls -l /var/tmp/test*
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060000
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060100
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060200
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060300
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060400
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060500

[test@test tmp]$ find /var/tmp/ -maxdepth 1 -type f -name "test*" ! -path $(find /var/tmp/ -type f -name "test*" -print0 | xargs -0r ls -1 | sort -r | head -1) -print0 | xargs -0r ls -l
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060000
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060100
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060200
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060300
-rw-r--r--. 1 test test 0 11月  6 09:08 2014 /var/tmp/test.201411060400

懸念

ファイル名不定の場合の例について、xargsの後のlsに-trオプションを付与することで日付順に並んでいるはずだが、結果ファイルが大量(xargsの結果復数のlsが起動される)の場合は綺麗に並ばない可能性がある
実運用上はファイル名パターンが決まっていてYYYYMMDDhhmmss順に並べたい…というような状況でのみ使うべきか。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3