Getting the line number of the nth match
If we're aiming to find the line number of the nth match, we might think to use grep and parse it's output.
Take this markdown document for example, where we want to find the line number of the second occurrence of ---:
input.md
---
title: some frontmatter
--- <-- We want the line number of this line
# Some contentgrep '^---$' -m 2 -n input.md | tail -1 | cut -d ":" -f 1This gets the job done, but it invokes a number of subshells, reducing performance. An alternative using awk may be less I/O intensive:
awk '/^---$/ && (++c == 2) { print NR; exit }' input.mdLast updated
Was this helpful?