From 9985e226228bc34b23700f57a8cd78394ae3b1e5 Mon Sep 17 00:00:00 2001 From: Jakob Kaivo Date: Fri, 29 Apr 2022 16:27:24 -0400 Subject: handle -x with regex --- grep.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/grep.c b/grep.c index 71a28c2..b508c77 100644 --- a/grep.c +++ b/grep.c @@ -48,7 +48,6 @@ static int grep_inverse = 0; static int grep_silent = 0; static int grep_exact = 0; -/* TODO: handle -x */ static int grep_match_re(struct grep_list *head, const char *buf) { for (struct grep_list *c = head; c != NULL; c = c->next) { @@ -176,8 +175,14 @@ static struct grep_list * grep_add_list(struct grep_list *head, char *s) tmp->next = node; } - node->string = strdup(pattern); - node->len = strlen(node->string); + /* reserve space for adding ^ and $ if needed */ + node->len = strlen(pattern); + node->string = malloc(node->len + 3); + if (node->string == NULL) { + perror("grep"); + exit(2); + } + strcpy(node->string, pattern); pattern = strtok(NULL, "\n"); } @@ -283,6 +288,12 @@ int main(int argc, char *argv[]) if (type != FIXED) { for (struct grep_list *c = head; c != NULL; c = c->next) { + if (grep_exact) { + memmove(c->string + 1, c->string, c->len); + c->string[0] = '^'; + c->string[c->len + 1] = '$'; + } + int e = regcomp(&(c->re), c->string, flags); if (e == 0) { free(c->string); -- cgit v1.2.1