Reputation: 70989
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.
Upvotes: 9
Views: 5497
Reputation: 85865
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
Upvotes: 3
Reputation: 63698
sed -n '1024,2048{/error/{=;p}}' | paste - -
Here /error/
is a pattern to match and =
prints the line number.
Upvotes: 7
Reputation: 29266
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)
Upvotes: 8