[英]How to delete the log messages in a file based on timestamp/ messages older than 7 days should be deleted from file
如何根據時間戳刪除文件中的日志消息/應該從文件中刪除早於 7 天的消息。
日志文件消息示例 -
2022-12-21T09:36:48+00:00 LONSTBYRDEV02 auth_log:
這些是文件中開頭帶有時間戳的行,我只想刪除所有超過 7 天的數據。 在這種情況下,考慮到今天的日期是 12 月 22 日,因此它應該刪除 12 月 15 日之前的所有行
你知道我可以在腳本中包含的任何命令或任何東西,並使用循環或其他東西刪除這些行嗎?
請建議。
任何人都可以根據上述情況提供幫助,在這種情況下,它應該刪除所有早於 12 月 15 日的行。
我已經寫了這篇文章,但沒有任何效果。
我的代碼-
current_DT=$(date +"%m-%d-%y-%T")
echo $current_DT
cutoff=$( date -d "7 days ago" +"%m-%d-%y-%T")
echo $cutoff
while read -r line ; do
timestamp=$( date -d "$( echo $line)" )
echo $timestamp
if [ $timestamp -gt $cutoff ] ; then
echo " Timestamp over cutoff old. Deleting lines."
sed -i "/^$hostname:/d" $hosts
fi
done
我得到的輸出是-
12-22-22-08:17:22
12-15-22-08:17:22
通常,對於日志,您會(正如@Gilles Quenot 在評論中所建議的那樣)使用logrotate
進行日志記錄。 我認為,出於某種原因,您需要一些不同的東西。
你可以反過來看:不是刪除舊的,而是保留 7 天。
#!/bin/bash
logfile="$1"
for i in $(seq 0 6) ; do
day=$(date +%Y-%m-%d -d -%{i}days)
grep "^${day}T" "$logfile"
done
也許另一種方法。 尋找較新的線路,然后停止。
# Set cutoff mark to start of file
mark=0
# Get cutoff time in seconds
cutoff=$( date -d '7 days ago' +%s )
# Loop through file
while read line
do
# Separate date
line_date=$( echo $line | cut -d' ' -f1 )
# Convert to seconds
line_sec=$( date +%s ${line_date} )
# If newer, get out of loop
[ ${line_sec} -gt ${cutoff} ] && break
# Move mark to next line
(( mark++ ))
done < my.log
# Delete older lines
sed -i "1,${count}d" my.log
使用 GNU 日期和任何 awk:
awk -v date="$(date -d'-7 days' +'%F')" '$1 >= date' file
這就是整個腳本,不需要循環。
如果你想更新原始文件然后使用 GNU awk for -i inplace
或使用無處不在的cmd file > tmp && mv tmp file
idiom 與任何 awk。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.