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


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 15.7 Getting a List of Matching Files with grep -l Chapter 15
Wildcards
Next: 15.9 nom: List Files that Don't Match a Wildcard
 

15.8 Getting a List of Non-Matching Files with grep -c

You can use the grep (27.2 ) option -c to tell you how many occurrences of a pattern appear in a given file, so you can also use it to find files that don't contain a pattern (i.e., zero occurrences of the pattern). Let's say you're indexing a troff (43.13 ) document and you want to make a list of files that don't yet contain indexing macros. What you need to find are files with zero occurrences of the string .XX . The command:

% grep -c "\.XX" chapter*

might produce the following output:

chapter1:10
chapter2:27
chapter3:19
chapter4:0
chapter5:39
   ...

This is all well and good, but suppose you need to check index entries in hundreds of reference pages? Well, just filter grep 's output by piping it through another grep . The above command can be modified as follows:

% grep -c "\.XX" chapter* | grep :0

This results in the following output:

chapter4:0

Using sed (34.24 ) to truncate the :0 , you can save the output as a list of files. For example, here's a trick for creating a list of files that don't contain index macros:

% grep -c "\.XX" * | sed -n s/:0//p > ../not_indexed.list

The sed -n command prints only the lines that contain :0 ; it also strips the :0 from the output so that ../not_indexed.list contains a list of files, one per line. The .. pathname (1.21 ) puts the not_indexed.list file into the parent directory - this is one easy way to keep grep from searching that file, but may not be worth the bother.

[To edit all files that need index macros added, you could type:

% vi `grep -c "\.XX" * | sed -n s/:0//p`

which is more obvious once you start using backquotes a lot. You can put this into a little script named vgrep with a couple of safety features added:





"$@"
 


#!/bin/sh
case $# in
0|1) echo "Usage: `basename $0` pattern file [files...]" 1>&2 ;;
*)  pat="$1"; shift
    grep -c "$pat" "$@" | sed -n 's/:0$//p'
   ;;
esac

Then you can type, for example, vi `vgrep "\.XX" *` . -JP  ]

- DG


Previous: 15.7 Getting a List of Matching Files with grep -l UNIX Power Tools Next: 15.9 nom: List Files that Don't Match a Wildcard
15.7 Getting a List of Matching Files with grep -l Book Index 15.9 nom: List Files that Don't Match a Wildcard

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