00001
00002
00003 #include "types.h"
00004 #include "stat.h"
00005 #include "user.h"
00006
00007 char buf[1024];
00008 int match(char*, char*);
00009
00010 void
00011 grep(char *pattern, int fd)
00012 {
00013 int n, m;
00014 char *p, *q;
00015
00016 m = 0;
00017 while((n = read(fd, buf+m, sizeof(buf)-m)) > 0){
00018 m += n;
00019 p = buf;
00020 while((q = strchr(p, '\n')) != 0){
00021 *q = 0;
00022 if(match(pattern, p)){
00023 *q = '\n';
00024 write(1, p, q+1 - p);
00025 }
00026 p = q+1;
00027 }
00028 if(p == buf)
00029 m = 0;
00030 if(m > 0){
00031 m -= p - buf;
00032 memmove(buf, p, m);
00033 }
00034 }
00035 }
00036
00037 int
00038 main(int argc, char *argv[])
00039 {
00040 int fd, i;
00041 char *pattern;
00042
00043 if(argc <= 1){
00044 printf(2, "usage: grep pattern [file ...]\n");
00045 exit();
00046 }
00047 pattern = argv[1];
00048
00049 if(argc <= 2){
00050 grep(pattern, 0);
00051 exit();
00052 }
00053
00054 for(i = 2; i < argc; i++){
00055 if((fd = open(argv[i], 0)) < 0){
00056 printf(1, "grep: cannot open %s\n", argv[i]);
00057 exit();
00058 }
00059 grep(pattern, fd);
00060 close(fd);
00061 }
00062 exit();
00063 }
00064
00065
00066
00067
00068 int matchhere(char*, char*);
00069 int matchstar(int, char*, char*);
00070
00071 int
00072 match(char *re, char *text)
00073 {
00074 if(re[0] == '^')
00075 return matchhere(re+1, text);
00076 do{
00077 if(matchhere(re, text))
00078 return 1;
00079 }while(*text++ != '\0');
00080 return 0;
00081 }
00082
00083
00084 int matchhere(char *re, char *text)
00085 {
00086 if(re[0] == '\0')
00087 return 1;
00088 if(re[1] == '*')
00089 return matchstar(re[0], re+2, text);
00090 if(re[0] == '$' && re[1] == '\0')
00091 return *text == '\0';
00092 if(*text!='\0' && (re[0]=='.' || re[0]==*text))
00093 return matchhere(re+1, text+1);
00094 return 0;
00095 }
00096
00097
00098 int matchstar(int c, char *re, char *text)
00099 {
00100 do{
00101 if(matchhere(re, text))
00102 return 1;
00103 }while(*text!='\0' && (*text++==c || c=='.'));
00104 return 0;
00105 }
00106