\$\begingroup\$
\$\endgroup\$
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 1
\$\begingroup\$
\$\endgroup\$
2
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
-
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\$glenn jackman– glenn jackman2017年08月22日 01:20:03 +00:00Commented Aug 22, 2017 at 1:20
-
\$\begingroup\$ You could write a bit shorter by replacing
{print}
with1
, for exampleawk '/bar/ {n++} n==2 {exit} 1' file
\$\endgroup\$janos– janos2017年08月22日 11:24:33 +00:00Commented Aug 22, 2017 at 11:24
lang-bash