LPD LPD - 1 year ago 73
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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download