grep match only lines in a specified range

Is it possible to use grep to match only lines with numbers in a pre-specified range? For instance I want to list all lines with numbers in the range [1024, 2048] of a log that contain the word 'error'.

I would like to keep the '-n' functionality ie have the number of the matched line in the file.


sed -n '1024,2048{/error/{=;p}}' | paste - -

此处/error/是匹配模式和=打印的行号。


Use sed first:

sed -ne '1024,2048p' | grep ...

-n says don't print lines, 'x,y,p' says print lines xy inclusive (overrides the -n)


Awk is a good tool for the job:

$ awk 'NR>=1024 && NR<=2048 && /error/ {print NR,$0}' file

In awk the variable NR contains the current line number and $0 contains the line itself.

The benefits with using awk is that you can easily change the output to display however you want it. For instance to separate the line number from line with a colon followed by a TAB:

$ awk 'NR>=1024 && NR<=2048 && /error/ {print NR,$0}' OFS=':t' file
链接地址: http://www.djcxy.com/p/19656.html

上一篇: grep匹配的行包括下面,另一个匹配的行包括上面

下一篇: grep仅匹配指定范围内的行