jac@yoko.rutgers.edu (Jonathan A. Chandross) (12/02/90)
Submitted-by: NONE
Posting-number: Volume 1, Source:13
Archive-name: util/fgrep
Architecture: ANY_2
Version-number: 1.00
This program is a fixed string pattern matcher (i.e. no regular
expressions).
Enjoy.
=fgrep.c
-/*
- *
- * fgrep.c
- *
- * Fast pattern matcher for fixed strings (no regular expressions).
- *
- * Usage:
- * fgrep [-nx] pattern [file_1] [file_2] [file_3] [...]
- *
- * Options:
- * -x print lines that do not patch pattern
- * -n print out line number
- *
- * If no file is specified, fgrep reads from standard in.
- *
- * Contributed Anonymously. Written: November 1983
- *
- * Version 1.00
- *
- */
-
-#include "stdio.h"
-
-#define TRUE 1
-#define FALSE 0
-#define MAXLINE 256
-#define BLANK ' '
-#define TAB '\t'
-#define NL '\n'
-#define EOS '\0'
-
-int numbering, except, files ;
-char *fname ;
-
-main(argc, argv)
-int argc ;
-char *argv[] ;
-{
- char *s, *pattern ;
- FILE *input ;
-
-
- numbering = except = files = FALSE ;
-
- while( --argc>0 && **++argv == '-' )
- for( s=&argv[0][1] ; *s != EOS ; s++ )
- switch( *s ) {
- case 'n':
- numbering = TRUE ;
- break ;
- case 'x':
- except = TRUE ;
- break ;
- default:
- fprintf(stderr, "fgrep: unknown option %c\n", *s ) ;
- argc = -1 ;
- break ;
- }
-
- if( argc <= 0 ) {
- fprintf(stderr, "usage: fgrep [-nx] pattern [files]\n");
- exit(1) ;
- }
-
- pattern = *argv ;
- argc-- ; argv++ ;
-
- if( argc > 1 )
- files = TRUE ;
-
- if( argc == 0 )
- fgrep( stdin, pattern ) ;
-
- else
- for( ; argc>0 ; argc--,argv++)
- if( (input=fopen(*argv,"r")) == NULL ) {
- fprintf(stderr, "fgrep: can't open %s\n", *argv) ;
- exit(1) ;
- }
- else {
- fname = *argv ;
- fgrep(input, pattern) ;
- fclose( input ) ;
- }
-
- exit(0) ;
-
-} /* end main */
-
-/* fgrep - match pattern to file */
-
-fgrep( in, pat )
-FILE *in ;
-char *pat ;
-{
- char line[ MAXLINE ], *fgets() ;
- int lines ;
-
-
- lines = 0 ;
- while( fgets(line, MAXLINE, in) != NULL ) {
- lines++ ;
- if( (match(line, pat) >= 0) != except ) {
- if( files )
- printf("%s: ", fname ) ;
- if( numbering )
- printf("%d: ", lines ) ;
- printf("%s", line ) ;
- }
- }
-
-} /* end fgrep */
-
-/* match - return index of pattern */
-
-match( subject, pattern )
-char *subject, *pattern ;
-{
- char *s, *p, *ss ;
-
- for( s=subject ; *s != EOS ; s++ ) {
- for( ss=s, p=pattern ; *p != EOS && *p == *ss ; p++, ss++ )
- ;
- if( *p == EOS )
- return s - subject ;
- }
-
- return -1 ;
-
-} /* end match */
-
-/* fgets - read a line from a file. */
-
-char *fgets(line, maxline, input)
-char *line ;
-int maxline ;
-FILE *input ;
-{
- int c ;
- char *start_line ;
-
- start_line = line;
-
- while( --maxline>0 && (c=agetc(input)) != EOF )
- if( (*line++ = c) == NL )
- break ;
-
- *line = 0 ;
- if( c == EOF && line == start_line )
- return(NULL) ;
- return(line) ;
-}
-
-
+ END OF ARCHIVE