根据可能位于特定列中任何位置的日期过滤文件

Filter file on dates that could be anywhere in a particular column

假设我有一个包含两列的文件:

blahblah2020-02-03_moreblah | VALUE |
blah2021-03-04blah | VALUE |

使用 awk,我只需要 select 第一列中的日期小于我拥有的其他日期的那些行。烦人的是,日期可能在任何一方的任何奇怪的字符串中,或​​者根本就是 none - 但它将采用 YYYY-mm-dd 格式。我不确定我是如何遇到必须使用 awk 的情况的,但我在这里,我提前非常感谢!

\d\d\d\d-\d\d-\d\d https://regexone.com/ 它有效,但有更好的解决方案 如果你想要它而不是通过收集所有日期然后根据之前的位置进行过滤来使用这种正则表达式语法在 pyhton 中编写一个脚本 - 无论那是大于还是小于你拥有的日期。 对于我在日期范围内: 如果日期 [i] < 正则表达式

假设:

  • 日期将始终采用 YYYY-MM-DD 格式(已在 OP 的描述中确认)
  • 任何感兴趣的日期将仅位于第一个 | 分隔字段中
  • 第一个字段最多只包含一个日期字符串(即,不必担心第一个字段包含多个日期字符串)

使用 GNU awk 4.0(或更新版本)获得 FPAT 支持:

awk -v testdt="${dt}" '                                        # pass bash variable "dt" in as awk variable "testdt"
BEGIN { FPAT="[12][0-9]{3}-[012][0-9]-[0123][0-9]"             # define pattern we are looking for; if exists it should be field #1
#       FPAT="[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}"    # one of a few alternatives
      }

 < testdt                                                    # if we have a match for FPAT and less than testdt then echo entire line to stdout
' input.dat

注意: 如果输入可能包含格式为 ####-##-## 的数据,这些数据不是有效日期,则 OP 可能需要调整 FPAT 定义and/or 添加更多逻辑以在 运行 测试之前将匹配验证为实际日期 ( < testdt)

此处使用 OP 的 2 行示例输入是使用不同值的 (bash) 变量的一些结果 dt:

$ dt='2019-06-01'
$ awk -v testdt="${dt}" 'BEGIN {FPAT="[12][0-9]{3}-[012][0-9]-[0123][0-9]"}  < testdt' input.dat
       -- no output --

$ dt='2020-06-01'
$ awk -v testdt="${dt}" 'BEGIN {FPAT="[12][0-9]{3}-[012][0-9]-[0123][0-9]"}  < testdt' input.dat
blahblah2020-02-03_moreblah | VALUE |

$ dt='2021-06-01'
$ awk -v testdt="${dt}" 'BEGIN {FPAT="[12][0-9]{3}-[012][0-9]-[0123][0-9]"}  < testdt' input.dat
blahblah2020-02-03_moreblah | VALUE |
blah2021-03-04blah | VALUE |

在每个 Unix 机器上,在任何 shell 中使用任何 awk:

$ awk -v tgt='2020-05-01' 'match([=10=],/[0-9]{4}(-[0-9]{2}){2}/) && (substr([=10=],RSTART,RLENGTH) < tgt)' file
blahblah2020-02-03_moreblah | VALUE |

$ awk -v tgt='2021-05-01' 'match([=10=],/[0-9]{4}(-[0-9]{2}){2}/) && (substr([=10=],RSTART,RLENGTH) < tgt)' file
blahblah2020-02-03_moreblah | VALUE |
blah2021-03-04blah | VALUE |