Simonlbc
Simonlbc

Reputation: 641

Printing the line number of the first occurence of a pattern starting from a specific line number in a file

How can one print the line number of the first occurence of the string foo in a file abc.text? I want the line of the first occurence as if abc.text started from it's 10th line.

Upvotes: 1

Views: 97

Answers (3)

Matei David
Matei David

Reputation: 2362

You could try:

awk 'NR>=10 && $0~/foo/ {print NR; exit}' abc.text

Explanations:

  • NR is the line number, only lines with number >=10 will be considered
  • if you want the output line number to ignore the first 9 lines, print NR-9
  • $0~/foo/ is standard pattern matching in awk
  • the exit will stop processing at the first occurrence

Upvotes: 2

Juan Tomas
Juan Tomas

Reputation: 5183

This may be more readable for some users:

tail -n +10 abc.txt | grep -n foo | head -1 | cut -f1 '-d:'

Upvotes: 0

janos
janos

Reputation: 124648

One way would be to use GNU sed this way:

sed -n '10,$ {/foo/{=; q}}' abc.text

That is:

  • In the range from line 10 to the end
  • -> For a line matching foo
  • -> Print the line number and then stop processing

Some tests to demonstrate the correctness:

{ for i in {1..9}; do echo $i; done; echo foo; echo bar; echo foo; } | \
sed -n '10,$ {/foo/{=; q}}'
# correctly prints 10

{ for i in {1..9}; do echo $i; done; echo x; echo foo; echo bar; echo foo; } | \
sed -n '10,$ {/foo/{=; q}}'
# correctly prints 11

{ for i in {1..9}; do echo $i; done; } | \
sed -n '10,$ {/foo/{=; q}}'
# correctly prints nothing

Upvotes: 2

Related Questions