From a file, I am trying to remove every line that include and follows the second occurrence of a given pattern in Bash (Mac OSX). Note, that a file may have only one match of the given pattern (and so nothing need to be removed).Here an example of filebarsecondthirdfourthbarsixthand here is a code that does the job# Find the index of the second occurrencei=$(grep -nrH ${pattern} ${file} | awk -F':' '{if (NR==2)print $2}')# If there was a second occurrence, then remove everything that followed itif [[ ${i} !=  ]];then    head -n $(( ${i} - 1 )) ${file} > tmp && mv tmp ${file};fiThe resulting file isbarsecondthirdfourthIs there a more elegant or faster solution?
Remove every line that include and follows the second occurrence of a given pattern
strings;regex;bash;awk;sed
This should be pretty speedy:awk '/bar/ {n++} n==2 {exit} {print}' fileTo pass the pattern from the shell:awk -v p=$pattern '$0 ~ p {n++} n==2 {exit} {print}' file