# Insert some text after Nth matching pattern using sed



## j4ck (Jul 4, 2013)

Hi*,*

Ho*w* can I do that?  I have multiple, e.g. foobar, patterns in my file, how can I add some_text after e.g. the 4fourth one?


----------



## lme@ (Jul 4, 2013)

I'd use awk(1) for this. Count the occurrences of foobar in a variable and sub() when the _n_'th occurrence is found.


----------



## j4ck (Jul 4, 2013)

Check this:
`sed -e :a -e '$!N' -e '$!ba' -e 's/\(TEXT_TO_FIND\)/\1\nNEW_TEXT_TO_INSERT/Nth_OCCURANCE' inputfile`


----------

