home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 15.6 Maybe You Shouldn't Use Wildcards in Pathnames Chapter 15
Wildcards
Next: 15.8 Getting a List of Non-Matching Files with grep -c
 

15.7 Getting a List of Matching Files with grep -l

Normally when you run grep (27.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 command:

% grep -l R5 

file1 file2 ... 

> r5.filelist

searches the files for a line containing the string R5 , produces a list of those filenames, and stores the list in r5.filelist . (This list might represent the files containing Release 5 documentation of a particular product.) Because these Release 5 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:

`...`
 
% print `cat r5.filelist`   

Print only the Release 5 files

% grep UNIX `cat r5.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 R5 , you would type:

% vi `grep -l R5 files

`

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 , JP


Previous: 15.6 Maybe You Shouldn't Use Wildcards in Pathnames UNIX Power Tools Next: 15.8 Getting a List of Non-Matching Files with grep -c
15.6 Maybe You Shouldn't Use Wildcards in Pathnames Book Index 15.8 Getting a List of Non-Matching Files with grep -c

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System