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?

dukevin
  • 1,630
  • 3
  • 18
  • 25
  • `^(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 09 '14 at 01: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 09 '14 at 01:31

1 Answers1

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.

jscott
  • 24,484
  • 8
  • 79
  • 100
  • 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 09 '14 at 01: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 09 '14 at 01:58
  • Hm why doesn't it match PLAYER_RENAMED in this: http://regexr.com/39f8n – dukevin Sep 09 '14 at 02:14
  • None of the "PLAYER_RENAMED" lines _also_ contain "duke" so what did you expect it to match on? – jscott Sep 09 '14 at 02:26