Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match once per file in grep?

Is there any grep option that let's me control total number of matches but stops at first match on each file?

Example:

If I do this grep -ri --include '*.coffee' 're' . I get this:

./app.coffee:express = require 'express' ./app.coffee:passport = require 'passport' ./app.coffee:BrowserIDStrategy = require('passport-browserid').Strategy ./app.coffee:app = express() ./config.coffee:    session_secret: 'nyan cat' 

And if I do grep -ri -m2 --include '*.coffee' 're' ., I get this:

./app.coffee:config = require './config' ./app.coffee:passport = require 'passport' 

But, what I really want is this output:

./app.coffee:express = require 'express' ./config.coffee:    session_secret: 'nyan cat' 

Doing -m1 does not work as I get this for grep -ri -m1 --include '*.coffee' 're' .

./app.coffee:express = require 'express' 

Tried not using grep e.g. this find . -name '*.coffee' -exec awk '/re/ {print;exit}' {} \; produced:

config = require './config'     session_secret: 'nyan cat' 

UPDATE: As noted below the GNU grep -m option treats counts per file whereas -m for BSD grep treats it as global match count

like image 476
pathikrit Avatar asked Oct 11 '12 02:10

pathikrit


People also ask

How do I grep exact match?

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.

Does grep stop after first match?

The grep command has an -m or --max-count parameter, which can solve this problem, but it might not work like you'd expect. This parameter will make grep stop matching after finding N matching lines, which works great as it will limit the output to one line, always containing the first match.


1 Answers

So, using grep, you just need the option -l, --files-with-matches.

All those answers about find, awk or shell scripts are away from the question.

like image 188
fenollp Avatar answered Sep 19 '22 15:09

fenollp