Grep matches only rows in the specified range

Can grep be used to match only strings with numbers in a predefined range? For example, I want to list all lines with numbers in a [1024, 2048]log range that contain the word "error."

I would like to keep the functionality of "-n", i.e. have a consistent line number in the file.

+5
source share
3 answers
sed -n '1024,2048{/error/{=;p}}' | paste - -

Here it /error/matches the pattern, and =prints the line number.

+5
source

Use sed first:

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

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

+7

Awk - :

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

The Awkvariable NRcontains the current line number, and $0contains the line.

The benefits of using it Awkare that you can easily change the output to display, but you want to use it. For example, to separate a line number from a colon line followed by a TAB:

$ awk 'NR>=1024 && NR<=2048 && /error/ {print NR,$0}' OFS=':\t' file
+3
source

All Articles