简体   繁体   English

Grep仅是文本文件的一部分

[英]Grep only a part of a text file

How can I apply the following command to only a part of a text file? 如何将以下命令仅应用于文本文件的一部分? For example from the beginning to the line 5000. 例如从一开始到5000行。

grep "^  A : 11  B : 10" filename | wc -l

I cannot use head and then apply the above command since the text file is huge. 由于文本文件很大,因此我不能使用head然后再应用上面的命令。

您可以尝试使用sed命令,从这个问题到管道,再到grep,我相信它对于大型文件会更好。

sed -n 1,5000p file | grep ...

You can try combination of -n (prefixing each line of output with line number) and -m (limiting number of matching lines). 您可以尝试-n(在输出的每一行前加上行号)和-m(限制匹配行数)的组合。 Something like this: 像这样:

grep -n -m 5000 pattern file.txt | grep -B 5000 "^5000:" | wc -l

First grep search for pattern, add line numbers and limit output to first 5000 matching lines (worst case scenario: all lines from range match pattern). 第一个grep搜索模式,添加行号并将输出限制为前5000个匹配行(最坏的情况:范围匹配模式中的所有行)。 Second grep match line number 5000, and print all lines before this line. 第二个grep匹配行号5000,并在此行之前打印所有行。

I don't know if it is more efficient solution 我不知道这是否是更有效的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM