Using grep

Posted:
in Genius Bar edited January 2014
I'm trying to use grep to search through a IRC log. For example if I want to find all instances of 'The_Ultimate_Samurai', I would *think* to search for .*Samurai and use the command 'grep .*Samurai .irclog'. But that isn't working. I can get it to work if I use 'grep .\\*Samurai .irclog', so I think that the shell was capturing the '*' from me, but in figuring that out I found something odd. 'grep .Samurai .irclog' works the same as 'grep .\\*Samurai .irclog'. This shouldn't be right. ".Samurai" should only match for one preceeding character, and ".*Samurai" should mean from zero to infinity preceeding characters but they seem to operate the same. I'm having a hard time figuring this out. Anyone can help me here?

Comments

  • Reply 1 of 2
    pyr3pyr3 Posts: 946member
    Ok, I've found that it is only tcsh that steals my '*' from me. Bash doesn't. Also I have found that the '.' works correctly when it is enclosed by letters. For example, "grep The.Samurai .irclog" won't find anything, but "grep The.*Samurai .irclog" will find everything it should. Why does the '.' work differently when it is on the front of the expression?
  • Reply 2 of 2
    thuh freakthuh freak Posts: 2,664member
    i'm pretty sure that grep adds an implicit * on both ends of your expression. if you use the option '-w' (or maybe its '-W') it takes off those darned implicit asterisks.



    also, for both shells, you can escape away your asterisk-losing problem.



    grep mysearch*string*with*stars*in*themiddle

    ...becomes...

    grep mysearch\\*string\\*with\\*stars\\*in\\*themiddle

    ...also, you can do quotes...

    grep "mysearch*string*with*stars*in*themiddle"

    ...and single quotes...

    grep 'mysearch*string*with*stars*in*themiddle'

    ...aaah, the magic of shells...
Sign In or Register to comment.