2

$DIR_TO_CLEAN数日以上前のファイルを削除したい$DAYS_TO_SAVE。簡単:

find "$DIR_TO_CLEAN" -mtime +$DAYS_TO_SAVE -exec rm {} \;

-type fにまたは-fフラグを追加できると思いrmますが、削除されたファイルの数を本当に数えたいと思います。

これは素朴に行うことができます:

DELETE_COUNT=`find "$DIR_TO_CLEAN" -mtime +$DAYS_TO_SAVE | wc -l`
find "$DIR_TO_CLEAN" -mtime +$DAYS_TO_SAVE -exec rm {} \;

しかし、この解決策には多くの課題が残されています。コマンドの重複に加えて、このスニペットはrm、ファイルの削除に失敗した場合のカウントを過大評価します。

私はリダイレクト、パイプ(名前付きのものを含む)、サブシェル、、などにかなり慣れていxargsますteeが、新しいトリックを学びたいと思っています。bashとkshの両方で機能するソリューションが欲しいです。

によって削除されたファイルの数をどのように数えますfindか?

4

2 に答える 2

5

I would avoid -exec and go for a piped solution:

find "$DIR_TO_CLEAN" -type f -mtime +$DAYS_TO_SAVE -print0 \
| awk -v RS='\0' -v ORS='\0' '{ print } END { print NR }'  \
| xargs -0 rm

Using awk to count matches and pass them on to rm.

Update:

kojiro made me aware that the above solution does not count the success/fail rate of rm. As awk has issues with badly named files I think the following bash solution might be better:

find "${DIR_TO_CLEAN?}" -type f -mtime +${DAYS_TO_SAVE?} -print0 |
(
  success=0 fail=0
  while read -rd $'\0' file; do 
  if rm "$file" 2> /dev/null; then 
    (( success++ ))
  else
    (( fail++ ))
  fi
  done
  echo $success $fail
)
于 2012-07-24T17:46:21.310 に答える
1
于 2012-07-24T17:39:38.817 に答える