繁体   English   中英

如何根据时间戳删除文件中的日志消息/应该从文件中删除早于 7 天的消息

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM