changeset 970:55794a3d35c5

grep: add -w flag
author Strake
date Sun, 08 Jun 2003 10:09:05 -0500
parents a47c6658210c
children 31e91deb0824
files toys/pending/grep.c
diffstat 1 files changed, 9 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/toys/pending/grep.c	Fri Jul 26 22:49:05 2013 -0500
+++ b/toys/pending/grep.c	Sun Jun 08 10:09:05 2003 -0500
@@ -5,13 +5,13 @@
  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/
  * See http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/cmdbehav.html
 
-USE_GREP(NEWTOY(grep, "EFHahinosvclqe*f*m#", TOYFLAG_BIN))
+USE_GREP(NEWTOY(grep, "EFHahinosvwclqe*f*m#", TOYFLAG_BIN))
 
 config GREP
   bool "grep"
   default n
   help
-    usage: grep [-clq] [-EFHhinosv] (-e RE | -f REfile | RE) [file...]
+    usage: grep [-clq] [-EFHhinosvw] (-e RE | -f REfile | RE) [file...]
 
     modes:
       default: print lines from each file what match regular expression RE.
@@ -29,6 +29,7 @@
       -o:   print only matching part
       -s:   keep silent on error
       -v:   invert match
+      -w:   match full word only
 */
 
 #define FOR_grep
@@ -48,7 +49,7 @@
 
   for (;;) {
     char *x, *y;
-    regmatch_t match;
+    regmatch_t matches[3];
     int atBOL = 1;
 
     x = get_rawline (fd, 0, '\n');
@@ -56,7 +57,7 @@
     y = x;
     n++; /* start at 1 */
 
-    while (regexec (&re, y, 1, &match, atBOL ? 0 : REG_NOTBOL) == 0) {
+    while (regexec (&re, y, 3, matches, atBOL ? 0 : REG_NOTBOL) == 0) {
       if (atBOL) nMatch++;
       toys.exitval = 0;
       atBOL = 0;
@@ -74,8 +75,8 @@
         if ( (toys.optflags & FLAG_n)) printf ("%d:", n);
         if (!(toys.optflags & FLAG_o)) fputs (x, stdout);
         else {
-          y += match.rm_so;
-          printf ("%.*s\n", match.rm_eo - match.rm_so, y++);
+          y += matches[2].rm_so;
+          printf ("%.*s\n", matches[2].rm_eo - matches[2].rm_so, y++);
         }
       }
       if (!(toys.optflags & FLAG_o)) break;
@@ -141,6 +142,8 @@
     toys.optc--; toys.optargs++;
   }
 
+  TT.re_xs = xmsprintf (toys.optflags & FLAG_w ? "(^|[^_[:alnum:]])(%s)($|[^_[:alnum:]])" : "()(%s)()", TT.re_xs);
+
   if (regcomp (&re, TT.re_xs,
                (toys.optflags & (FLAG_E | FLAG_F) ? REG_EXTENDED : 0) |
                (toys.optflags &  FLAG_i           ? REG_ICASE    : 0)) != 0) {