user/grep.c
107 lines
1// Simple grep. Only supports ^ . * $ operators.23#include "kernel/types.h"4#include "kernel/stat.h"5#include "kernel/fcntl.h"6#include "user/user.h"78char buf[1024];9int match(char*, char*);1011void12grep(char *pattern, int fd)13{14 int n, m;15 char *p, *q;1617 m = 0;18 while((n = read(fd, buf+m, sizeof(buf)-m-1)) > 0){19 m += n;20 buf[m] = '\0';21 p = buf;22 while((q = strchr(p, '\n')) != 0){23 *q = 0;24 if(match(pattern, p)){25 *q = '\n';26 write(1, p, q+1 - p);27 }28 p = q+1;29 }30 if(m > 0){31 m -= p - buf;32 memmove(buf, p, m);33 }34 }35}3637int38main(int argc, char *argv[])39{40 int fd, i;41 char *pattern;4243 if(argc <= 1){44 fprintf(2, "usage: grep pattern [file ...]\n");45 exit(1);46 }47 pattern = argv[1];4849 if(argc <= 2){50 grep(pattern, 0);51 exit(0);52 }5354 for(i = 2; i < argc; i++){55 if((fd = open(argv[i], O_RDONLY)) < 0){56 printf("grep: cannot open %s\n", argv[i]);57 exit(1);58 }59 grep(pattern, fd);60 close(fd);61 }62 exit(0);63}6465// Regexp matcher from Kernighan & Pike,66// The Practice of Programming, Chapter 9, or67// https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html6869int matchhere(char*, char*);70int matchstar(int, char*, char*);7172int73match(char *re, char *text)74{75 if(re[0] == '^')76 return matchhere(re+1, text);77 do{ // must look at empty string78 if(matchhere(re, text))79 return 1;80 }while(*text++ != '\0');81 return 0;82}8384// matchhere: search for re at beginning of text85int matchhere(char *re, char *text)86{87 if(re[0] == '\0')88 return 1;89 if(re[1] == '*')90 return matchstar(re[0], re+2, text);91 if(re[0] == '$' && re[1] == '\0')92 return *text == '\0';93 if(*text!='\0' && (re[0]=='.' || re[0]==*text))94 return matchhere(re+1, text+1);95 return 0;96}9798// matchstar: search for c*re at beginning of text99int matchstar(int c, char *re, char *text)100{101 do{ // a * matches zero or more instances102 if(matchhere(re, text))103 return 1;104 }while(*text!='\0' && (*text++==c || c=='.'));105 return 0;106}107108