Search code examples
bashawkgrepnumbersline

How to get the line number of nth match?


Let's say I have the following file:

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

Let's say I want to find the line number of the second match for cat, how can I do that?


Solution

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

    count the cats, print the line number and exit after the required match value.