Reputation: 641
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
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 consideredprint NR-9
$0~/foo/
is standard pattern matching in awk
exit
will stop processing at the first occurrenceUpvotes: 2
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
Reputation: 124648
One way would be to use GNU sed this way:
sed -n '10,$ {/foo/{=; q}}' abc.text
That is:
foo
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