我在 CentOS 中有一个巨大的网络服务器 access.log。我通过远程 VPN 访问它,因此无法复制文件或直接读取它。
我知道我想要复制的日志中的具体时间,但它太早了,太容易将日志的尾部复制到文本文件中。这是一行日志的样子。
10.255.16.203 - - [26/Mar/2014:16:35:13 +0000]
所以我的问题是:如果我知道要查找的时间字符串,如何复制非常大的日志的特定部分?
答案1
该grep
命令旨在仅显示给定文件的匹配行。通过使用-C
选项,不仅可以显示匹配的行,还可以显示其之前和之后的一些行。
因此,要在您想要的行之前和之后添加 3 行:
$ grep -C 3 "26/Mar/2014:16:35:13 +0000" access.log
-A
您还可以使用和选项更精确地调整匹配行之后和/或之前显示的行数-B
。其实-C 3
是一样的-A 3 -B 3
。
如果有多个匹配行,则将grep
显示匹配行块之前和之后的 3 行。
例子:
$ grep -C 3 "25/Mar/2014:10:40:59 +0100" access.log
10.0.0.44 - httpuse [25/Mar/2014:09:41:17 +0100] "GET /dummy/BIGDummy_133644_1565_DL.xml.gz HTTP/1.1" 200 507 "-" "-"
10.0.0.43 - httpuse [25/Mar/2014:09:59:51 +0100] "GET /dummy/BIGDummy_133647_48267_DL.xml.gz HTTP/1.1" 200 1677 "-" "-"
10.0.0.44 - httpuse [25/Mar/2014:10:40:42 +0100] "GET /dummy/BIGDummy_133664_39603_DL.xml.gz HTTP/1.1" 200 1677 "-" "-"
10.0.0.40 - httpuse [25/Mar/2014:10:40:59 +0100] "GET /dummy/BIGDummy_133664_DL.xml.gz HTTP/1.1" 200 60142 "-" "-"
10.0.0.41 - httpuse [25/Mar/2014:10:40:59 +0100] "GET /dummy/BIGDummy_133667_23124_DL.xml.gz HTTP/1.1" 200 5202 "-" "-"
10.0.0.40 - httpuse [25/Mar/2014:10:43:09 +0100] "GET /dummy/BIGDummy_133668_46_DL.xml.gz HTTP/1.1" 200 445 "-" "-"
10.0.0.42 - httpuse [25/Mar/2014:10:43:10 +0100] "GET /dummy/BIGDummy_133668_4116_DL.xml.gz HTTP/1.1" 200 597 "-" "-"
10.0.0.40 - httpuse [25/Mar/2014:10:43:13 +0100] "GET /dummy/BIGDummy_133665_DL.xml.gz HTTP/1.1" 200 57902 "-" "-"
从man grep
:
NAME
grep, egrep, fgrep - print lines matching a pattern
SYNOPSIS
grep [options] PATTERN [FILE...]
DESCRIPTION
Grep searches the named input FILEs (or standard input if no files are named,
or the file name - is given) for lines containing a match to the given PATTERN.
By default, grep prints the matching lines.
OPTIONS
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing -- between contiguous groups of matches.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing -- between contiguous groups of matches.
-C NUM, --context=NUM
Print NUM lines of output context.
Places a line containing -- between contiguous groups of matches.