Richard Rublev Richard Rublev - 2 months ago 9
Linux Question

grep,how to search for exact pattern?

This was what I have tried

grep -n 'qtrain' *.m

But I got also

SKSC.m:195:model.qtrain = model.qtrainExtra(:,k-1);
SKSC.m:196:model.mqtrain = model.mqtrainExtra{k-1};
SKSC.m:197:model.sqtrain = model.sqtrainExtra{k-1};

How to get rid of the others?
I just want exact match with my pattern.


If by "exact pattern" you mean a complete line with only qtrain in it, then use the -x flag:

grep -nx qtrain *.m

This will only match lines that contain exactly "qtrain" and nothing else.

If by "exact pattern" you mean to match "qtrain" but not "blahqtrain" or "qtrainblah", then you can use -w to match whole words:

grep -nw qtrain *.m

This will match only this line in your input:

SKSC.m:195:model.qtrain = model.qtrainExtra(:,k-1);

Btw, here's another equivalent way using regular expressions:

grep -n '\<qtrain\>' *.m

From man grep:

The symbols \< and \> respectively match the empty string at the beginning and end of a word.