Remove every line that include and follows the second occurrence of a given pattern 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 file

bar
second
third
fourth
bar
sixth


and here is a code that does the job

# Find the index of the second occurrence
i=$(grep -nrH ${pattern} ${file} | awk -F':' '{if (NR==2)print $2}')

# If there was a second occurrence, then remove everything that followed it
if [[ ${i} != "" ]];then
    head -n $(( ${i} - 1 )) ${file} &gt; tmp &amp;&amp; mv tmp ${file};
fi


The resulting file is

bar
second
third
fourth


Is there a more elegant or faster solution?
This should be pretty speedy:

awk '/bar/ {n++} n==2 {exit} {print}' file


To pass the pattern from the shell:

awk -v p="$pattern" '$0 ~ p {n++} n==2 {exit} {print}' file