[PATCH v2 2/2] findutils/grep.c: Short-circuit -v to bail out on first match

Ari Sundholm ari at tuxera.com
Mon Jan 28 17:41:12 UTC 2019


A small optimization. There is no need to try matching the current
input line against any further patterns if a match was already
found and -v is specified.

Signed-off-by: Ari Sundholm <ari at tuxera.com>
Signed-off-by: Niko Vähäsarja <niko at tuxera.com>
---
v2: Make the code more readable and modify the relevant comment

 findutils/grep.c | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/findutils/grep.c b/findutils/grep.c
index 9d9da422c..0251e8082 100644
--- a/findutils/grep.c
+++ b/findutils/grep.c
@@ -443,10 +443,18 @@ static int grep_file(FILE *file)
 					}
 				}
 			}
-			/* If it's non-inverted search, we can stop
-			 * at first match */
-			if (found && !invert_search)
-				goto do_found;
+			/* If it's a non-inverted search, we can stop
+			 * at first match and report it.
+			 * If it's an inverted search, we can move on
+			 * to the next line of input, ignoring the
+			 * rest of the patterns.
+			 */
+			if (found) {
+				if (invert_search)
+					break;
+				else
+					goto do_found;
+			}
 			pattern_ptr = pattern_ptr->link;
 		} /* while (pattern_ptr) */
 
-- 
2.17.1



More information about the busybox mailing list