1

I have a log file with a list of many entries. With grep regex I want to match the first word and another word which can be anywhere in the string.

For example, if I specified "user1" the search would search:

grep -E '^(IP_CONNECT|IP_DISCONNECT) user1' file.txt

However this won't match unless user1 is at the beginning of the string whereas I want to match it if it appears anywhere in the string. How is this done?

2
  • ^(IP_CONNECT|IP_DISCONNECT) user1 means "start of line followed by IP_CONNECT or IP_DISCONNECT, then a single space, then user1". Is this really what you want to match on?
    – jscott
    Sep 9, 2014 at 1:29
  • No I want to match "start of line followed by IP_CONNECT or IP_DISCONNECT and somewhere in that line user1 must be present"
    – dukevin
    Sep 9, 2014 at 1:31

1 Answer 1

1

I think you mean you want to match lines that begin with either "IP_CONNECT" or "IP_DISCONNECT", followed by one or more of [most] any characters, followed by "user1".

grep -E '^(IP_CONNECT|IP_DISCONNECT).+user1' file.txt

You also might find tools like regexpal helpful in exploring this.

4
  • Thanks! A side question: Is this fairly inefficient for huge files? Would there possibly be a more efficient command/method such as knowing how many spaces before the match?
    – dukevin
    Sep 9, 2014 at 1:53
  • Inefficient in which ways? I can't say that I've benched marked "less specific" vs "more specific" regexes to provide a useful answer.
    – jscott
    Sep 9, 2014 at 1:58
  • Hm why doesn't it match PLAYER_RENAMED in this: regexr.com/39f8n
    – dukevin
    Sep 9, 2014 at 2:14
  • None of the "PLAYER_RENAMED" lines also contain "duke" so what did you expect it to match on?
    – jscott
    Sep 9, 2014 at 2:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .