LPD LPD - 5 months ago 11x
Linux Question

Regext to match only ONE occurance of a pattern

How to write a regex that says that given pattern is present ONLY once?

for e.g.. if am searching for pattern 'file',

123file345 --> Match
asdffile12 --> match
file12file --> does not match


You could use a negative lookahead:


Test at regex101

You may apply the above regex in grep.

grep -P '^(?!(?:.*?file){2}).*?file' file

The negative lookahead assertion at ^ start (?!(?:.*?file){2}) looks ahead, if there's not
2x ( .*? lazily any amount of any characters, followed by substring file ).
If this condition succeeds, it matches .*?file.* all string if it contains substring file.

For just matching the line the last greedy dot (to match any characters after file) is not required.

enter image description here