Sifting Through Files for a String

Problem

You need to find all occurrences of a string in one or more files.

Solution

The grep command searches through files looking for the expression you supply:

$ grep printf *.c
both.c:    printf("Std Out message.\n", argv[0], argc-1);
both.c:    fprintf(stderr, "Std Error message.\n", argv[0], argc-1);
good.c:    printf("%s: %d args.\n", argv[0], argc-1);
somio.c:        // we'll use printf to tell us what we
somio.c:        printf("open: fd=%d\n", iod[i]);
$

The files we searched through in this example were all in the current directory. We just used the simple shell pattern *.c to match all the files ending in .c with no preceding pathname.

Not all the files through which you want to search may be that conveniently located. Of course, the shell doesn’t care how much pathname you type, so we could have done something like this:

$ grep printf ../lib/*.c ../server/*.c ../cmd/*.c */*.c

Discussion

When more than one file is searched, grep begins its output with the filename, followed by a colon. The text after the colon is what actually appears in the files that grep searched.

The search matches any occurrence of the characters, so a line that contained the string “fprintf” was returned, since “printf” is contained within “fprintf”.

The first (non-option) argument to grep can be just a simple string, as in this example, or it can be a more complex regular expression (RE). These REs are not the same as the shell’s pattern matching, though they can look similar at times. Pattern ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.