4
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

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
\$\endgroup\$
2
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Aug 22, 2017 at 1:20
  • \$\begingroup\$ You could write a bit shorter by replacing {print} with 1, for example awk '/bar/ {n++} n==2 {exit} 1' file \$\endgroup\$
    – janos
    Aug 22, 2017 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.