如果日期早于30天,请使用bash删除文本文件中的行 [英] remove line in text file with bash if the date is older than 30 days

查看:51
本文介绍了如果日期早于30天,请使用bash删除文本文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,如下所示:

I have a text file that looks like this:

test10 2016-05-30 207
test11 2016-06-01 207
test12 2016-07-20 207
test13 2016-07-21 207
test14 2016-07-25 207

如果该日期早于30天,我想从文本文件中删除这些行.我怎样才能做到这一点?我已经读过一些sed,但不确定是否可以完成或如何进行.

And I want to remove the lines from the text file if that date is older than 30 days. How can I do this? I have read some aboud sed but not sure if it can be done or how to go about doing it.

推荐答案

关于YYYY-MM-DD的好处是,其alpha排序与作为日期对象的排序顺序相同-因此,您只需生成一个字符串即可代表截止日期并与之进行比较.

The nice thing about YYYY-MM-DD is that its alpha sort is identical to its sort order as a date object -- so you can just generate a string representing the cutoff date and compare to that.

如果您有GNU日期:

cutoff=$(date -d 'now - 30 days' '+%Y-%m-%d')
awk -v cutoff="$cutoff" '$2 >= cutoff { print }' <in.txt >out.txt && mv out.txt in.txt

还可以依靠GNU awk(gawk)而不是GNU日期:

It's also possible to rely on GNU awk (gawk) rather than GNU date:

gawk -v current="$(date +"%Y %m %d %H %M %S")" \
  'BEGIN {
     cutoff_secs = mktime(current) - (60 * 60 * 24 * 30)
   }

   {
     line_secs=mktime(gensub(/-/, " ", "g", $2) " 00 00 00")
     if (line_secs >= cutoff_secs) { print }
   }' <in.txt >out.txt && mv out.txt in.txt

请注意,后一种实现在30天前的当前时间开始,而不是30天前的开始;如果您不希望出现这种情况,请用00 00 00替换%H %M %S.

Note that the latter implementation starts at the current time 30 days ago, rather than at the beginning of the day 30 days ago; replace %H %M %S with 00 00 00 if you don't want this behavior.

这篇关于如果日期早于30天,请使用bash删除文本文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆