Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep match only lines in a specified range

Tags:

linux

grep

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 i.e. have the number of the matched line in the file.

like image 407
Ivaylo Strandjev Avatar asked Jun 19 '12 07:06

Ivaylo Strandjev


3 Answers

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

Here /error/ is a pattern to match and = prints the line number.

like image 163
Prince John Wesley Avatar answered Sep 25 '22 21:09

Prince John Wesley


Use sed first:

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

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

like image 31
John3136 Avatar answered Sep 24 '22 21:09

John3136


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
like image 42
Chris Seymour Avatar answered Sep 21 '22 21:09

Chris Seymour