如何在grep中每个文件一次匹配? [英] How to match once per file in grep?
问题描述
是否有任何grep选项可以让我控制匹配的总数,但在每个文件的第一个匹配处停止?
Is there any grep option that let's me control total number of matches but stops at first match on each file?
示例:
如果我这样做grep -ri --include '*.coffee' 're' .
我会得到:
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'
如果我执行grep -ri -m2 --include '*.coffee' 're' .
,我会得到:
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'
执行-m1
无效,因为我得到了grep -ri -m1 --include '*.coffee' 're' .
Doing -m1
does not work as I get this for grep -ri -m1 --include '*.coffee' 're' .
./app.coffee:express = require 'express'
尝试不使用grep,例如此find . -name '*.coffee' -exec awk '/re/ {print;exit}' {} \;
产生的:
Tried not using grep e.g. this find . -name '*.coffee' -exec awk '/re/ {print;exit}' {} \;
produced:
config = require './config'
session_secret: 'nyan cat'
更新:如下所述,GNU grep -m
选项将每个文件计数视为计数,而BSD grep的-m
将其视为全局匹配计数
UPDATE: As noted below the GNU grep -m
option treats counts per file whereas -m
for BSD grep treats it as global match count
推荐答案
我认为您可以做类似的事情
I think you can just do something like
grep -ri -m1 --include '*.coffee' 're' . | head -n 2
例如从每个文件中选择第一个匹配项,然后最多选择两个匹配项.
to e.g. pick the first match from each file, and pick at most two matches total.
请注意,这要求您的grep
将-m
视为每个文件的匹配限制; GNU grep
会这样做,但是BSD grep
显然将其视为全局匹配限制.
Note that this requires your grep
to treat -m
as a per-file match limit; GNU grep
does do this, but BSD grep
apparently treats it as a global match limit.
这篇关于如何在grep中每个文件一次匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!