ログファイルから古いログを削除する

ログファイルから古いログを削除する

私は2年間毎日複数のログファイルを追加してきました。過去数年間の日付を含めることができますか?たとえば、90..1000は3ヶ月以上のファイルから過去数年間のファイルを削除しますか?

ベストアンサー1

ログファイルを手動で管理するのは複雑です。ログファイルはどのように使用されますか?定期的に更新されますか、または長期実行プロセス(デーモン)が継続的に開かれていますか?後者の場合は、デーモンで何かをする必要があります(信号を送信または再起動する)。manデーモンページを読んでください。

ログファイル(big.log)がどのプロセスでも開かれていない場合(検査を介して)、sudo lsof $PWD/big.logコマンドdateman date)を ""および" "書式設定オプションと一緒に使用して、90日より古いログファイルを使用されたものと同じ形式で生成します。--date="today - 90 days"+big.log

# Warning: bash pseudo-code due to fuzziness of spec
# Warning: run any derived code through https://shellcheck.net
# **UNTESTED**
# You: Backup big.log, Just In Case

longago="$(date --date="today - 90 days" +"%...")"
# find the line number of the first occurence of the long ago date. 
# only want the 1st match, 
# only want the line number (up to the colon)
firstkeep="$(grep -n "$longago" big.log | head -n1 | cut -d: -f1)"
# left as an exercise: what if there are no logs on $longago?
# simple check? 
[[ -z "$firstkeep" ]] && \
    error ...
# now, just keep from $firstkeep to the end
tail -n "$firstkeep" big.log
 >small.log

# now, check small.log (add tests)
wc -l big.log small.log

# when you're satisfied with small.log

# If the first mv works, do the second
mv big.log big.log.old && mv small.log big.log

# finally, when you're satisfied with the new, smaller big.log.
df.;rm big.log.old;df .

これらすべてのコマンドにはmanページがあります。必要に応じてお読みくださいman bash

おすすめ記事