我有一个在第7列包含日期的文件,我的要求是将它与今天的日期进行比较,如果它早于今天的日期,则删除完整的行。此外,如果第7栏中提到的任何日期大于15天,则将其修改为最大15天
下面的例子:
now="$(date +'%d-%m-%Y')"
now=24-02-2021
file.txt
abc xyz pqr NFS 5 abc.vol
abc xyz pqr NFS 50 xyz.bal 23-02-2021
abc xyz pqr NFS 5 abcd.xyz
abc xyz pqr NFS 15 pqr.vol 25-02-2023
abc xyz pqr NFS 5 xyz.bal 24-03-2021
abc xyz pqr NFS 3 pqrst.vol 19-01-2019
输出应为-
abc xyz pqr NFS 5 abc.vol
abc xyz pqr NFS 5 abcd.xyz
abc xyz pqr NFS 15 pqr.vol 11-03-2021
abc xyz pqr NFS 5 xyz.bal 24-03-2021
我试过awk,但它完全不起作用
awk -v d=$now '$7 == "" && $7 < d' file.txt
发布于 2021-02-24 22:21:14
尝试以下GNU awk解决方案:
awk 'NF == 6 { print;next } { OFS="\t";split($7,map,"-");depoch=mktime(map[3]" "map[2]" "map[1]" 00 00 00");if (depoch<systime()) { next };if (+depoch>(systime()+1296000)) { $7=strftime("%d-%m-%Y",(systime()+1296000)) } }1' file.txt
解释:
awk 'NF == 6 { print; # If there is no date, print the line and skip to the next
next
}
{ OFS="\t"; # Set the output field delimiter to tab
split($7,map,"-"); # Split the date into the array map (getting day, month and year)
depoch=mktime(map[3]" "map[2]" "map[1]" 00 00 00"); # Create epoch format of the date
if (depoch<systime()) {
next # If epoch format of date is less than today, skip to the next record
};
if (depoch>(systime()+1296000)) {
$7=strftime("%d-%m-%Y",(systime()+1296000)) # If the date is greater than today +15 days, set the date to the date + 15 days (1296000 seconds) and format accordingly using strftime
}
}1' file.txt
我假设发布的所需输出是不正确的。24-03-2021从今天起大于15天,因此应更改为11-03-2021
发布于 2021-02-24 14:41:41
你在正确的轨道上,试着在你的代码中改变你的条件部分。它不起作用的原因是你要求awk
程序检查第七个字段是否为空,同时它的值小于变量,这意味着执行相同的条件,换句话说,如果第七个字段为空,那么肯定会小于上述日期。为了得到实际不为空的结果,并且从当前日期开始具有较小的日期,根据您的当前条件,您将只获得第7个字段基本上为空的那些字段,因此,如果第7个字段为空或小于今天的日期,则将其更改为OR条件以获取行,然后简单地打印它。
now="$(date +'%d-%m-%Y')"
awk -v d=$now '$7 == "" || $7 < d' Input_file
https://stackoverflow.com/questions/66345824
复制相似问题