我有一个日志文件,其中包含以下数据:
2019-02-11 00:05:58.241 [exec-178] Start request
2019-02-11 00:05:58.242 [exec-178] customer_name
2019-02-11 00:05:58.243 [exec-178] other process
2019-02-11 00:05:58.244 [exec-178] other process
2019-02-11 00:05:58.245 [exec-178] results
2019-02-11 00:05:58.246 [exec-178] End request (13ms)
我想使用单个 grep 命令来捕获“customer_name”和“End request”。我一直在尝试使用,grep -E "[0-9]{2,4}ms
但它没有提供预期的输出。
预期输出:
2019-02-11 00:05:58.242 [exec-178] customer_name
2019-02-11 00:05:58.246 [exec-178] End request (13ms)
答案1
可以使用grep -E
grep 查找的模式由管道符号分隔。
[root@server ~]# grep -Ei "customer_name|end request" file
2019-02-11 00:05:58.242 [exec-178] customer_name
2019-02-11 00:05:58.246 [exec-178] End request (13ms)
[root@server ~]#
摘自man grep
:
-E, --extended-regexp 将 PATTERN 解释为扩展正则表达式(ERE,见下文)。
-i, --ignore-case 忽略 PATTERN 和输入文件中的大小写区别。
答案2
使用 搜索固定字符串grep
非常简单。您可以grep
使用以下选项传递多个模式-e
:
$ cat testfile
2019-02-11 00:05:58.241 [exec-178] Start request
2019-02-11 00:05:58.242 [exec-178] customer_name
2019-02-11 00:05:58.243 [exec-178] other process
2019-02-11 00:05:58.244 [exec-178] other process
2019-02-11 00:05:58.245 [exec-178] results
2019-02-11 00:05:58.246 [exec-178] End request (13ms)
$ grep -F -e 'customer_name' -e 'End request' testfile
2019-02-11 00:05:58.242 [exec-178] customer_name
2019-02-11 00:05:58.246 [exec-178] End request (13ms)
该-F
选项用于指定您正在搜索固定字符串。这并不是很有必要,但它有助于使命令更加明确。
您还可以使用扩展的正则表达式来简单地执行该命令。表达式 A|B 用于搜索“A”或“B”。
$ grep -E 'customer_name|End request' testfile
2019-02-11 00:05:58.242 [exec-178] customer_name
2019-02-11 00:05:58.246 [exec-178] End request (13ms)
答案3
如果您只想返回位于单独行上的确切字符串:
egrep -o "customer_name|End request" logfile
输出:
customer_name
End request
如果您希望它返回整行:
egrep "customer_name|End request" logfile
输出
2019-02-11 00:05:58.242 [exec-178] customer_name
2019-02-11 00:05:58.246 [exec-178] End request (13ms)
答案4
要获取搜索行之间(包括搜索行)的所有内容,请使用 awk:
awk 'BEGIN {found=0}; /customer_name/ {found=1}; found {print}; /End request/ {found=0}' logfile
如果您的“customer_name”不是静态字符串,而是不同的值,请尝试使用-v
,例如:
awk -v "name=sally" 'BEGIN {found=0}; index($0, name) {found=1}; found {print}; /End request/ {found=0}' logfile
或者有更好的格式和解释,但更难复制和粘贴:
awk -v "name=sally" 'BEGIN {
# good style, but optional... nonexistent variables are already 0
found=0;
};
index($0, name) {
# remember that we found the first line
found=1;
};
found {
# since we print after the found=1, we print that line
# and also the lines between
# and since we set found=0 after already printing the end line, we are printing that too
print;
};
/End request/ {
# mark that we stop printing
found=0;
};' logfile