Handle null BRE/ERE and do not add a pattern to the list if it already exists

This commit is contained in:
sin 2014-11-20 16:45:22 +00:00
parent 7627a5069c
commit 5ba4f37ec3

19
grep.c
View File

@ -134,17 +134,30 @@ addpattern(const char *pattern)
struct pattern *pnode; struct pattern *pnode;
char *tmp; char *tmp;
pnode = emalloc(sizeof(*pnode)); /* a null BRE/ERE matches every line */
if (!Fflag)
if (pattern[0] == '\0')
pattern = ".";
if (!Fflag && xflag) { if (!Fflag && xflag) {
tmp = emalloc(strlen(pattern) + 3); tmp = emalloc(strlen(pattern) + 3);
snprintf(tmp, strlen(pattern) + 3, "%s%s%s", snprintf(tmp, strlen(pattern) + 3, "%s%s%s",
pattern[0] == '^' ? "" : "^", pattern[0] == '^' ? "" : "^",
pattern, pattern,
pattern[strlen(pattern) - 1] == '$' ? "" : "$"); pattern[strlen(pattern) - 1] == '$' ? "" : "$");
pnode->pattern = tmp;
} else { } else {
pnode->pattern = estrdup(pattern); tmp = estrdup(pattern);
} }
SLIST_FOREACH(pnode, &phead, entry) {
if (!strcmp(pnode->pattern, tmp)) {
free(tmp);
return;
}
}
pnode = emalloc(sizeof(*pnode));
pnode->pattern = tmp;
SLIST_INSERT_HEAD(&phead, pnode, entry); SLIST_INSERT_HEAD(&phead, pnode, entry);
} }