Grep: show only first match per line?

Hi,

can I make grep stop after finding the first occurrence of a regex in a line?

Given:

file with various regex patterns
file to be grep'ed

Sadly some of the regex patterns cannot be limited any further, so

grep -Eiof patterns.txt file.txt

(GNU grep 2.20) will give me possibly n hits for one line of the "source". But I only need the first hit per line.

Can I do this with grep?

And if grep is not my friend (in this case), how can I reach the goal instead? With an awk or sed loop? :confused:

Thank you!

Stephan

Show the input you have, and show the output you want.

grep is going to show the whole line unless the c or s option is used. You could used sed to insert escape sequences around your searched for term to make the first one stand out (apply a color or invert the display).

1 Like

How about

awk '
NR == FNR       {SRCH = SRCH DL $0
                 DL = "|"
                 next
                }
match ($0, SRCH){print substr ($0, RSTART, RLENGTH)
                }
' patterns.txt file.txt
1 Like

Thank you RudiC! That's exactly what I needed!
Many regards
Stephan