简体   繁体   中英

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.

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

I cannot use head and then apply the above command since the text file is huge.

您可以尝试使用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). 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). Second grep match line number 5000, and print all lines before this line.

I don't know if it is more efficient solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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