33.6. Getting a List of Matching Files with grep -l
Normally when you run grep (Section 13.1) on a group of files, the output lists the filename along with the line containing the search pattern. Sometimes you want to know only the names of the files, and you don't care to know the line (or lines) that match. In this case, use the -l (lowercase letter "l") option to list only filenames where matches occur. For example, the following command:
% grep -l R6 file1 file2 ... > r6.filelist
searches the files for a line containing the string R6, produces a list of those filenames, and stores the list in r6.filelist. (This list might represent the files containing Release 6 documentation of a particular product.) Because these Release 6 files can now be referenced by one list, you can treat them as a single entity and run various commands on them all at once:
'...' Section 28.14
% lpr `cat r6.filelist` Print only the Release 6 files % grep UNIX `cat r6.filelist` Search limited to the Release 5 files
You don't have to create a file list, though. You can insert the output of a grep directly into a command line with command substitution. For example, to edit only the subset of files containing R6, you would type:
% vi `grep -l R6 file1 file2 ...`
(Of course, you also could use a wildcard like file* instead of a list of filenames.)
grep -l is also good for shell programs that need to check whether a file contains a particular string. The traditional way to do that test is by throwing away grep's output and checking its exit status:
if grep something somefile >/dev/null then ...
If somefile is huge, though, grep has to search all of it. Adding the grep -l option saves time because grep can stop searching after it finds the first matching line.
--DG and JP
Copyright © 2003 O'Reilly & Associates. All rights reserved.