34

質問:ディレクトリ内の最新の 3 つを除くすべてのファイルを削除するにはどうすればよいですか?

最新の 3 つのファイルを見つけるのは簡単です。

ls -t | head -3

しかし、最新の 3 つのファイルを除くすべてのファイルを検索する必要があります。そのために不要な for ループを作成せずに、同じ行でこれらのファイルを削除するにはどうすればよいですか?

これには Debian Wheezy と bash スクリプトを使用しています。

4

11 に答える 11

9
ls -t | tail -n +4 | xargs -I {} rm {}

1ライナーをご希望の場合

于 2014-11-05T19:25:09.017 に答える
2

ディレクトリごとに保持する任意の数のファイルを含む再帰スクリプト

スペース、改行、その他の奇妙な文字を含むファイル/ディレクトリも処理します

#!/bin/bash
if (( $# != 2 )); then
  echo "Usage: $0 </path/to/top-level/dir> <num files to keep per dir>"
  exit
fi

while IFS= read -r -d $'\0' dir; do
  # Find the nth oldest file
  nthOldest=$(find "$dir" -maxdepth 1 -type f -printf '%T@\0%p\n' | sort -t '\0' -rg \
    | awk -F '\0' -v num="$2" 'NR==num+1{print $2}')

  if [[ -f "$nthOldest" ]]; then
    find "$dir" -maxdepth 1 -type f ! -newer "$nthOldest" -exec rm {} +
  fi
done < <(find "$1" -type d -print0)

コンセプトの証明

$ tree test/
test/
├── sub1
│   ├── sub1_0_days_old.txt
│   ├── sub1_1_days_old.txt
│   ├── sub1_2_days_old.txt
│   ├── sub1_3_days_old.txt
│   └── sub1\ 4\ days\ old\ with\ spaces.txt
├── sub2\ with\ spaces
│   ├── sub2_0_days_old.txt
│   ├── sub2_1_days_old.txt
│   ├── sub2_2_days_old.txt
│   └── sub2\ 3\ days\ old\ with\ spaces.txt
└── tld_0_days_old.txt

2 directories, 10 files
$ ./keepNewest.sh test/ 2
$ tree test/
test/
├── sub1
│   ├── sub1_0_days_old.txt
│   └── sub1_1_days_old.txt
├── sub2\ with\ spaces
│   ├── sub2_0_days_old.txt
│   └── sub2_1_days_old.txt
└── tld_0_days_old.txt

2 directories, 5 files
于 2020-05-05T19:27:34.733 に答える