[hackers] [sbase][PATCH] grep: Fix -x, simplify addpattern

From: Santtu Lakkala <inz_AT_inz.fi>
Date: Thu, 6 Nov 2025 15:24:08 +0200

Use grouping for -x to make \| / | work correctly; as a bonus beginning
and end of line anchors hold their special meaning inside a group,
removing the need for special handling of them.

Further, as this makes -w and -x only differ in anchors used, use the
same code for both.
---
 grep.c | 31 ++++++++++---------------------
 1 file changed, 10 insertions(+), 21 deletions(-)
diff --git a/grep.c b/grep.c
index f541d44..397f649 100644
--- a/grep.c
+++ b/grep.c
_AT_@ -41,31 +41,20 @@ addpattern(const char *pattern)
 {
 	struct pattern *pnode;
 	char *tmp;
-	int bol, eol;
-	size_t len, patlen;
+	size_t patlen;
 
 	patlen = strlen(pattern);
-	bol = pattern[0] == '^';
-	eol = patlen > 0 && pattern[patlen - 1] == '$';
 
-	if (!Fflag && xflag) {
-		tmp = enmalloc(Error, patlen + 3);
-		snprintf(tmp, patlen + 3, "%s%s%s",
-			 bol ? "" : "^",
-			 pattern,
-			 eol ? "" : "$");
-	} else if (!Fflag && wflag) {
-		len = patlen + 5 + (Eflag ? 2 : 4);
-		tmp = enmalloc(Error, len);
-
-		snprintf(tmp, len, "%s\\<%s%.*s%s\\>%s",
-		         bol ? "^" : "",
-		         Eflag ? "(" : "\\(",
-		         (int)patlen - bol - eol, pattern + bol,
-		         Eflag ? ")" : "\\)",
-		         eol ? "$" : "");
-	} else {
+	if (Fflag || (!xflag && !wflag)) {
 		tmp = enstrdup(Error, pattern);
+	} else {
+		tmp = enmalloc(Error, patlen + 9);
+		sprintf(tmp, "%s%s%s%s%s",
+			xflag ? "^" : "\\<",
+			Eflag ? "(" : "\\(",
+			pattern,
+			Eflag ? ")" : "\\)",
+			xflag ? "$" : "\\>");
 	}
 
 	pnode = enmalloc(Error, sizeof(*pnode));
-- 
2.42.0
Received on Thu Nov 06 2025 - 14:24:08 CET

This archive was generated by hypermail 2.3.0 : Thu Nov 06 2025 - 14:24:52 CET