Richard Rublev
Richard Rublev

Reputation: 8164

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.

Upvotes: 1

Views: 6104

Answers (3)

Johnathan Andersen
Johnathan Andersen

Reputation: 258

Do you only want it to return "qtrain"? If so, you probably want to use

grep -no qtrain *.m

If you were hoping it would only match lines in which "qtrain" was the only text, use

grep -n ^qtrain$ *.m

Upvotes: 1

G Dan
G Dan

Reputation: 96

You could also just do

grep -n '\.qtrain' *.m

To get anything with ".qtrain". Note that you have to escape the dot while grepping

Upvotes: 1

janos
janos

Reputation: 124648

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.

Upvotes: 4

Related Questions