2011-05-23 01:36:34 +00:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
|
|
|
#include <regex.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
2011-05-24 00:13:34 +00:00
|
|
|
#include <unistd.h>
|
2011-05-23 01:36:34 +00:00
|
|
|
|
|
|
|
static void grep(FILE *, const char *, regex_t *);
|
|
|
|
|
|
|
|
static bool iflag = false;
|
|
|
|
static bool vflag = false;
|
|
|
|
static bool many;
|
|
|
|
static bool match = false;
|
|
|
|
static char mode = 0;
|
|
|
|
|
|
|
|
int
|
|
|
|
main(int argc, char *argv[])
|
|
|
|
{
|
2011-05-24 00:13:34 +00:00
|
|
|
char c;
|
|
|
|
int flags = 0;
|
2011-05-23 01:36:34 +00:00
|
|
|
regex_t preg;
|
|
|
|
FILE *fp;
|
|
|
|
|
2011-05-24 00:13:34 +00:00
|
|
|
while((c = getopt(argc, argv, "cilnqv")) != -1)
|
|
|
|
switch(c) {
|
|
|
|
case 'c':
|
|
|
|
case 'l':
|
|
|
|
case 'n':
|
|
|
|
case 'q':
|
|
|
|
mode = c;
|
|
|
|
break;
|
|
|
|
case 'i':
|
2011-05-23 01:36:34 +00:00
|
|
|
iflag = true;
|
2011-05-24 00:13:34 +00:00
|
|
|
break;
|
|
|
|
case 'v':
|
2011-05-23 01:36:34 +00:00
|
|
|
vflag = true;
|
|
|
|
break;
|
2011-05-24 00:13:34 +00:00
|
|
|
default:
|
2011-05-24 10:05:36 +00:00
|
|
|
exit(2);
|
2011-05-24 00:13:34 +00:00
|
|
|
}
|
|
|
|
if(optind == argc) {
|
|
|
|
fprintf(stderr, "usage: %s [-cilnqv] pattern [files...]\n", argv[0]);
|
2011-05-23 01:36:34 +00:00
|
|
|
exit(2);
|
|
|
|
}
|
|
|
|
if(mode == 'c')
|
|
|
|
flags |= REG_NOSUB;
|
|
|
|
if(iflag)
|
|
|
|
flags |= REG_ICASE;
|
2011-05-24 00:13:34 +00:00
|
|
|
regcomp(&preg, argv[optind++], flags);
|
2011-05-23 01:36:34 +00:00
|
|
|
|
2011-05-24 00:13:34 +00:00
|
|
|
many = (argc > optind+1);
|
|
|
|
if(optind == argc)
|
2011-05-23 01:36:34 +00:00
|
|
|
grep(stdin, "<stdin>", &preg);
|
2011-05-24 00:13:34 +00:00
|
|
|
else for(; optind < argc; optind++) {
|
|
|
|
if(!(fp = fopen(argv[optind], "r"))) {
|
|
|
|
fprintf(stderr, "fopen %s: ", argv[optind]);
|
2011-05-23 01:36:34 +00:00
|
|
|
perror(NULL);
|
|
|
|
exit(2);
|
|
|
|
}
|
2011-05-24 00:13:34 +00:00
|
|
|
grep(fp, argv[optind], &preg);
|
2011-05-23 01:36:34 +00:00
|
|
|
fclose(fp);
|
|
|
|
}
|
|
|
|
return match ? 0 : 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
grep(FILE *fp, const char *str, regex_t *preg)
|
|
|
|
{
|
|
|
|
char buf[BUFSIZ];
|
|
|
|
int n, c = 0;
|
|
|
|
|
|
|
|
for(n = 1; fgets(buf, sizeof buf, fp); n++) {
|
|
|
|
if(regexec(preg, buf, 0, NULL, 0) ^ vflag)
|
|
|
|
continue;
|
|
|
|
if(mode == 'c')
|
|
|
|
c++;
|
|
|
|
else if(mode == 'l') {
|
|
|
|
puts(str);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
else if(mode == 'q')
|
|
|
|
exit(0);
|
|
|
|
else {
|
|
|
|
if(many)
|
|
|
|
printf("%s:", str);
|
|
|
|
if(mode == 'n')
|
|
|
|
printf("%d:", n);
|
|
|
|
fputs(buf, stdout);
|
|
|
|
}
|
|
|
|
match = true;
|
|
|
|
}
|
|
|
|
if(mode == 'c')
|
|
|
|
printf("%d\n", c);
|
|
|
|
if(ferror(fp)) {
|
|
|
|
fprintf(stderr, "%s: read error: ", str);
|
|
|
|
perror(NULL);
|
|
|
|
exit(2);
|
|
|
|
}
|
|
|
|
}
|