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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With