第一个问题是date 调用,虽然从awk 脚本中调用是可行的,但如果我们在ksh 中进行调用,将结果存储在ksh 变量中会更容易,并且然后使用-v 选项将此变量传递给awk。
第二个问题是混合使用 (awk) 变量和正则表达式进行模式匹配;我发现先构建一个正则表达式模式然后使用该模式进行实际的模式匹配会更容易一些。
但首先是一些数据……假设“今天”是 2021 年 3 月 23 日:
$ cat pfrmi.log
[Mar 9, 2019 8:53:36 AM] ProcessFlow RMI Server started at: 10.155.166.24:16003 - skip this line
[Mar 23, 2021 8:53:36 AM] ProcessFlow RMI Server started at: 10.155.166.24:16003 - pick this line
[Nov 18, 2019 8:53:36 AM] some other TOT Server started at: 10.155.166.24:16003 - skip this line
[Mar 23, 2021 8:53:36 AM] ProcessFlow RMI Server started at: 10.155.166.24:16003 - pick this line
[Mar 23, 2021 8:53:36 AM] ProcessFlow RMI Server started at: 10.155.166.24:16003 - skip this line
[Nov 18, 2020 8:53:36 AM] ProcessFlow RMI Server started at: 10.155.166.24:16003 - skip this line
现在建议的代码:
$ today=$(date '+%b %d, %Y')
$ echo "${today}"
Mar 23, 2021
$ awk -v today="${today}" ' # pass ksh variable into awk
BEGIN { ptn="^[[]"today" .*RMI Server started" } # build our regex pattern
$0 ~ ptn # test current line against our regex and if it matches the line will be passed to stdout
' pfrmi.log
对于我的示例数据文件,这会生成:
[Mar 23, 2021 8:53:36 AM] ProcessFlow RMI Server started at: 10.155.166.24:16003 - pick this line
[Mar 23, 2021 8:53:36 AM] ProcessFlow RMI Server started at: 10.155.166.24:16003 - pick this line
将awk 折叠成单行命令并删除 cmets:
awk -v today="${today}" 'BEGIN { ptn="^[[]"today" .*RMI Server started" } $0 ~ ptn' pfrmi.log