我有一个要求,如果模式匹配,我需要从日志文件中grep多个字符串
下面是日志快照:access.log
12.12.137.16 - RMC1 [06/Jul/2016:07:34:17 -0700] "GET /identity/afr/partition/ie/n/default/opt/grid-11.1.1.9.0-5358.js HTTP/1.1" 200 9318
12.12.137.16 - BMC1 [06/Jul/2016:07:34:17 -0700] "GET /identity/ HTTP/1.1" 200 6788
12.12.137.16 - RMC1 [06/Jul/2016:07:34:17 -0700] "GET /identity/afr/partition/ie/n/default/opt/status-11.1.1.9.0-5358.js HTTP/1.1" 200 2297
12.12.137.16 - RMC1 [06/Jul/2016:07:34:17 -0700] "GET /identity/afr/partition/ie/n/default/opt/poll-11.1.1.9.0-5358.js HTTP/1.1" 200 2098
12.12.137.16 - RMC1 [06/Jul/2016:07:34:18 -0700] "GET /identity/afr/alta-v1/overflow_right_ena.png HTTP/1.1" 200 1082
12.12.137.16 - RMC1 [06/Jul/2016:07:34:18 -0700] "GET /identity/ HTTP/1.1" 200 6749
12.12.137.16 - RMC1 [06/Jul/2016:07:34:18 -0700] "GET /identity/afr/alta-v1/conv_l_ena.png HTTP/1.1" 200 1161
12.12.137.16 - RMC1 [06/Jul/2016:07:34:24 -0700] "GET /identity/ HTTP/1.1" 200 6799
12.12.137.16 - RMC1 [06/Jul/2016:07:34:27 -0700] "GET /identity/images/Dashboard/myAccess_s2.png HTTP/1.1" 200 6885
12.12.137.16 - SSS1 [06/Jul/2016:07:34:24 -0700] "POST /identity/faces/home?_adf.ctrl-state=o9l9q161v_5 HTTP/1.1" 200 41776
如果模式与日志文件中的/identity /HTTP/1.1
匹配
所以我的输出将是:
BMC1 06/Jul/2016:07:34:17
RMC1 06/Jul/2016:07:34:18
RMC1 06/Jul/2016:07:34:24
尝试:
grep -E '/identity/ HTTP/1.1' *.log
但它是全线。
请协助
答案 0 :(得分:4)
$ awk -F'[][ ]+' '/\/identity\/ HTTP\/1[.]1/{print $3,$4}' access.log
BMC1 06/Jul/2016:07:34:17
RMC1 06/Jul/2016:07:34:18
RMC1 06/Jul/2016:07:34:24
工作原理:
-F'[][ ]+'
这会将字段分隔符设置为[
,]
或空格的任意组合。
/\/identity\/ HTTP\/1[.]1/{print $3,$4}
这将选择感兴趣的行并仅打印第三和第四个字段。
$ sed -n '\|/identity/ HTTP/1[.]1|{s/^.* - //; s/[[]//; s/[]].*//; p;}' access.log
BMC1 06/Jul/2016:07:34:17 -0700
RMC1 06/Jul/2016:07:34:18 -0700
RMC1 06/Jul/2016:07:34:24 -0700
工作原理:
-n
除非我们明确要求,否则告诉sed不要打印任何内容。
\|/identity/ HTTP/1[.]1|
选择感兴趣的行。
s/^.* - //; s/[[]//; s/[]].*//
对于选定的行,这三个替换命令会从行中删除不需要的部分。
p
这告诉sed在我们进行替换后打印所选行的剩余部分。
grep -P
如果你的grep支持-P
标志:
$ grep -oP '(?<= - ).*(?= "GET /identity/ HTTP/1\.1)' access.log
BMC1 [06/Jul/2016:07:34:17 -0700]
RMC1 [06/Jul/2016:07:34:18 -0700]
RMC1 [06/Jul/2016:07:34:24 -0700]
如果摆脱[
和]
很重要,我们可以使用:
$ grep -oP '(?<= - ).*(?=] "GET /identity/ HTTP/1\.1)' access.log | tr -d '['
BMC1 06/Jul/2016:07:34:17 -0700
RMC1 06/Jul/2016:07:34:18 -0700
RMC1 06/Jul/2016:07:34:24 -0700