Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash find chained to a grep which then prints

Tags:

grep

find

I have a series of index files for some data files which basically take the format

index file : asdfg.log.1234.2345.index

data file : asdfg.log

The idea is to do a search of all the index files. If the value XXXX appears in an index file, go and grep its corresponding data file and print out the line in the data file where the value XXXX appears.

So far I can simply search the index files for the value XXXX e.g.

find . -name "*.index" | xargs grep "XXXX"     // Gives me a list of the index files with XXXX in them

How do I take the index file match and then grep its corresponding data file?

like image 974
wmitchell Avatar asked Jul 20 '10 13:07

wmitchell


People also ask

How do you use grep to find lines ending with the pattern?

Matching the lines that end with a string : The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern. 11. -f file option Takes patterns from file, one per line.

How do I print grep output?

The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.

How do you use find and grep?

To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'. By default, grep searches for a pattern in a case-sensitive way.


1 Answers

Does this do the trick?

find . -name '*.index' |
xargs grep -l "XXXX" |
sed 's/\.log\.*/.log/' |
xargs grep "XXXX"

The find command is from your example. The first xargs grep lists just the (index) file names. The sed maps the file names to the data file names. The second xargs grep then scans the data files.

You might want to insert a sort -u step after the sed step.

like image 125
Jonathan Leffler Avatar answered Sep 20 '22 23:09

Jonathan Leffler