简体   繁体   中英

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!!!?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM