Regex – Exclude regex bash script

grepregex

I want to find the lastlogin on certain usernames. I want to exclude anything starting with qwer* and root but keep anything with user.name

Here is what I have already, but the last part of the regex doesn't work. Any help appreciated.

lastlog | egrep '[a-zA-Z]\.[a-zA-Z]|[^qwer*][^root]'

Best Solution

That regexp doesn't do what you think it does. Lets break it down:

  • [a-zA-Z] - the [...] denotes a character class. What you have means: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z (and the capital versions). This captures a single character! That's not what you want!
  • \. - this is a period. Needs the backslash since . means "any character".
  • [a-zA-Z] - same as above.
  • | - or sign. Either what came before, or what comes afterwards.
  • [^qwer*] - Captures any single character that's not q, w, e, r, or *.
  • [^root] - Captures any single character that's not r, o, or t.

As you can see, that's not exactly what you were going for. Try the following:

lastlog | egrep -v '^(qwer|root$)' | egrep '^[a-zA-Z]+\.[a-zA-Z]+$'

You can't have "don't match this group" operator in regexps... That's not regular. Some implementations do provide such functionality anyway, namely PCRE and Python's re package.