在bash中使用awk比较日期 [英] comparing dates using awk in bash

查看:245
本文介绍了在bash中使用awk比较日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个文件,每行都有一些信息和日期(生日).我想在给定日期之后打印带有日期的行.我使用此awk命令

So I have a file and each line has some info and a date (birthday). And I want to print the lines with dates after a given date. I use this awk command

awk -F '|' 'FNR>1 $dateA<=$5 {print $1" "$2" "$3" "$4" "$5" "$6" "$7" "$8}' $FILE

但是它不能正常工作(所有文件行都已打印).日期采用YYYY-MM-DD格式,因此字母顺序也按时间顺序排列.

But it doesnt work properly (all file lines are printed). The dates are in YYYY-MM-DD format so alphabetical order is also chronological.

输入文件中的某些行

1099511628908|Chen|Wei|female|1985-08-02|2010-05-24T20:52:26.582+0000|27.98.244.108|Firefox
1099511633435|Smith|Jack|male|1981-04-19|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer
1099511635042|Kiss|Gyorgy|male|1984-09-14|2010-05-16T22:57:41.808+0000|91.137.244.86|Chrome
1099511635218|Law-Yone|Eric|male|1987-01-20|2010-05-26T20:10:22.515+0000|203.81.95.235|Chrome
1099511638444|Jasani|Chris|female|1981-05-22|2010-04-29T20:50:40.375+0000|196.223.11.62|Firefox
2199023256615|Arbelaez|Gustavo|male|1986-11-02|2010-07-17T18:53:47.633+0000|190.96.218.101|Chrome

推荐答案

正如其他人所说,shell不会扩展单引号中的变量. Awk将看到变量的名称,而不是其值.

As it was said by others, a variable in single quotes will not be expanded by the shell. Awk will see the name of the variable, not its value.

一种可能的解决方案是执行此操作(假设比较字符串正确):

One possible solution is to do this (assuming comparing strings is correct):

dateA='1985-01-01'
infile='file to read values from'
awk -F '|' -v dateA="$dateA" '{if (FNR>1 && dateA<=$5) {print}}' "$infile"

一种更惯用的解决方案(有点不清楚):

A more idiomatic solution (a bit less clear is):

awk 'FNR>1 && dateA<=$5' FS='|' dateA="$dateA" "$infile"

或(是,需要所有引号):

Or (yes, all the quoting is needed):

awk 'FNR>1 && "'"$dateA"'"<=$5' FS='|' "$infile"

但是,甚至在考虑使用此选项之前,请阅读有关代码注入的信息.

But before even thinking of using this option read this about code injection.

这篇关于在bash中使用awk比较日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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