1 // Simple grep. Only supports ^ . * $ operators.
8 int match(char*, char*);
11 grep(char *pattern
, int fd
)
17 while((n
= read(fd
, buf
+m
, sizeof(buf
)-m
)) > 0){
20 while((q
= strchr(p
, '\n')) != 0){
22 if(match(pattern
, p
)){
38 main(int argc
, char *argv
[])
44 printf(2, "usage: grep pattern [file ...]\n");
54 for(i
= 2; i
< argc
; i
++){
55 if((fd
= open(argv
[i
], 0)) < 0){
56 printf(1, "grep: cannot open %s\n", argv
[i
]);
65 // Regexp matcher from Kernighan & Pike,
66 // The Practice of Programming, Chapter 9.
68 int matchhere(char*, char*);
69 int matchstar(int, char*, char*);
72 match(char *re
, char *text
)
75 return matchhere(re
+1, text
);
76 do{ // must look at empty string
77 if(matchhere(re
, text
))
79 }while(*text
++ != '\0');
83 // matchhere: search for re at beginning of text
84 int matchhere(char *re
, char *text
)
89 return matchstar(re
[0], re
+2, text
);
90 if(re
[0] == '$' && re
[1] == '\0')
92 if(*text
!='\0' && (re
[0]=='.' || re
[0]==*text
))
93 return matchhere(re
+1, text
+1);
97 // matchstar: search for c*re at beginning of text
98 int matchstar(int c
, char *re
, char *text
)
100 do{ // a * matches zero or more instances
101 if(matchhere(re
, text
))
103 }while(*text
!='\0' && (*text
++==c
|| c
=='.'));