如何获取第n个匹配的行号?

How to get the line number of nth match?

假设我有以下文件:

* cat
* dog
* cat
* fish
* fish
* cat
* turtle

假设我想找到 cat 的第二个匹配项的行号,我该怎么做?

$ awk '/cat/{c++} c==2{print NR;exit}' file
3

统计猫数,打印行号并在所需的匹配值后退出。

awk 解决方案更 I/O 有效,但我想指出还有一个纯粹的 shell 解决方案:

grep -n cat | head -2 | tail -n 1 | cut -d: -f1

请随意用任何其他正则表达式替换 cat。