试图调试服务器的一个问题,我唯一的日志文件是一个20GB的日志文件(甚至没有时间戳!)为什么人们使用System.out.println()作为日志?在生产吗? !)

使用grep,我找到了我想要查看的文件区域,第347340107行。

除了做一些

head -<$LINENUM + 10> filename | tail -20 

... 这将需要头读取日志文件的前3.47亿行,是否有一个快速而简单的命令将行347340100 - 347340200(例如)转储到控制台?

我完全忘记了grep可以打印匹配前后的上下文…这很有效。谢谢!


当前回答

不,没有,文件不是行寻址的。

在文本文件中,没有固定时间的方法来找到第n行的开始。您必须流遍文件并计算换行符。

使用你拥有的最简单/最快的工具来完成这项工作。对我来说,使用head比使用grep更有意义,因为后者要复杂得多。我并不是说“grep很慢”,它确实不是,但是如果它比head更快,我会感到惊讶。那基本上就是脑袋里的虫子了。

其他回答

我很惊讶,只有另一个答案(由Ramana Reddy)建议在输出中添加行号。下面搜索所需的行号并为输出上色。

file=FILE
lineno=LINENO
wb="107"; bf="30;1"; rb="101"; yb="103"
cat -n ${file} | { GREP_COLORS="se=${wb};${bf}:cx=${wb};${bf}:ms=${rb};${bf}:sl=${yb};${bf}" grep --color -C 10 "^[[:space:]]\\+${lineno}[[:space:]]"; }

用sed -e '1,N d;M q'你将打印从N+1到M的行,这可能比grep -C更好一点,因为它不会尝试将行与模式匹配。

我发现了其他两个解决方案,如果你知道行号,但没有其他(没有grep可能):

假设你需要第20到40行,

sed -n '20,40p;41q' file_name

or

awk 'FNR>=20 && FNR<=40' file_name

When using sed it is more efficient to quit processing after having printed the last line than continue processing until the end of the file. This is especially important in the case of large files and printing lines at the beginning. In order to do so, the sed command above introduces the instruction 41q in order to stop processing after line 41 because in the example we are interested in lines 20-40 only. You will need to change the 41 to whatever the last line you are interested in is, plus one.

Use

x=`cat -n <file> | grep <match> | awk '{print $1}'`

在这里,您将获得发生匹配的行号。

现在可以使用下面的命令打印100行

awk -v var="$x" 'NR>=var && NR<=var+100{print}' <file>

或者你也可以使用“sed”

sed -n "${x},${x+100}p" <file>

Sed还需要读取数据来计算行数。 唯一可能的快捷方式是文件中有上下文/顺序可以操作。例如,如果日志行前面有固定宽度的时间/日期等。 您可以使用look Unix实用程序在文件中查找特定的日期/时间