# 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} > tmp && mv tmp ${file}; fi  The resulting file is bar second third fourth  Is there a more elegant or faster solution? ## 1 Answer 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

• Generally, if you find yourself mixing grep and awk and sed in a pipeline, you can replace all of it with a single awk program. – glenn jackman Aug 22 '17 at 1:20
• You could write a bit shorter by replacing {print} with 1, for example awk '/bar/ {n++} n==2 {exit} 1' file – janos Aug 22 '17 at 11:24