我有一个包含以下条目的文件
Command : apply
Log File : /u01/test/123.log
Command : list
Log File : /u01/test/456.log
Command : rollback
Log File : /u01/test/123.log
我的目的是查找应用/回退命令,然后在日志文件中查找特定字符串“ Make failed” 正在查看awk范围模式,但感到困惑...请告知
答案 0 :(得分:0)
我认为关键是使用multi-line record processing而不是范围模式。
如果您有一个名为commands-and-logs.txt
的文件,其中包含以下内容(我在示例内容中加上了/tmp/
,以便可以创建文件进行测试):
Command : apply
Log File : /tmp/u01/test/123.log
Command : list
Log File : /tmp/u01/test/456.log
Command : rollback
Log File : /tmp/u01/test/123.log
您可以运行:
awk -v RS="" -v FS="[:\n]" '$2 ~ /apply|rollback/ {print $4}' commands-and-logs.txt | sort -u | xargs grep -n "Make failed" /dev/null
。
对我来说,/tmp/u01/test/123.log
包含:
Line with Make failed 1
Line without...
Line without...
Line with Make failed 2
Line with Make failed 3
Line without...
和/tmp/u01/test/456.log
包含:
Line without anything interesting...
Line with Make failed 4
Line with Make failed 5
Line without...
Line without...
我提供的命令会打印:
/tmp/u01/test/123.log:1:Line with Make failed 1
/tmp/u01/test/123.log:4:Line with Make failed 2
/tmp/u01/test/123.log:5:Line with Make failed 3
打破这一点:
-v
选项表示“在Awk中设置此变量”。RS
和FS
表示设置记录和字段分隔符。RS
设置为特殊值""
以使用多行记录的信息。FS
设置为正则表达式的信息。在这种情况下,使字段分隔符为正则表达式[:\n]
有意义,即“冒号或换行符”。尝试使用awk -v RS="" -v FS="[:\n]" '{printf("$1: %s, $2: %s, $3: %s, $4: %s\n", $1, $2, $3, $4)}' commands-and-logs.txt
来了解如何拆分字段。$2 ~ /apply|rollback/
的意思是“仅向我显示 Command 为'apply'或'rollback'的条目。” print $4
打印第四个字段(日志文件名)。sort -u
,所以我不会多次搜索文件。xargs grep
搜索匹配的日志文件。我将/dev/null
附加到基于this trick的参数列表中,以便始终在匹配的行旁边列出文件名。我希望这会有所帮助。