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?

asked Aug 21, 2017 at 23:37
\$\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
answered Aug 22, 2017 at 1:17
\$\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\$ Commented 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\$ Commented Aug 22, 2017 at 11:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.