NoobEditor
NoobEditor

Reputation: 15881

Confusion on grep pattern search

Consider this log file

SN      PID     Date                            Status
1       P01     Fri Feb 14 19:32:36 IST 2014    Alive
2       P02     Fri Feb 14 19:32:36 IST 2014    Alive
3       P03     Fri Feb 14 19:32:36 IST 2014    Alive
4       P04     Fri Feb 14 19:32:36 IST 2014    Alive
5       P05     Fri Feb 14 19:32:36 IST 2014    Alive
6       P06     Fri Feb 14 19:32:36 IST 2014    Alive
7       P07     Fri Feb 14 19:32:36 IST 2014    Alive
8       P08     Fri Feb 14 19:32:36 IST 2014    Alive
9       P09     Fri Feb 14 19:32:36 IST 2014    Alive
10      P010    Fri Feb 14 19:32:36 IST 2014    Alive

When i do => grep "P01" File
output is : (as expected)

1       P01     Fri Feb 14 19:32:36 IST 2014    Alive
10      P010    Fri Feb 14 19:32:36 IST 2014    Alive

But when i do => grep " P01 " File (notice the space before and after P01)
I do not get any output!

Question : grep matches pattern in a line, so " P01 " ( with space around ) should match the first PID of P01 as it has spaces around it....but seems that this logic is wrong....what obvious thing i am missing here!!!?

Upvotes: 0

Views: 77

Answers (1)

glenn jackman
glenn jackman

Reputation: 246799

If the log uses tabs not spaces, your grep pattern won't match. I would add word boundaries to the word you want to find:

grep '\<P01\>' file

If you really want to use whitespace in your pattern, use one of:

grep '[[:blank:]]P01[[:blank:]]' file    # horizontal whitespace, tabs and spaces
grep -P '\sP01\s' file                   # using Perl regex

Upvotes: 2

Related Questions