ibash
ibash

Reputation: 741

Exclude regex bash script

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]'

Upvotes: 6

Views: 16170

Answers (2)

cha0site
cha0site

Reputation: 10717

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.

Upvotes: 7

Lee Netherton
Lee Netherton

Reputation: 22482

This should do you:

lastlog | egrep -v '^qwer|^root$'

The -v option to grep gives you the non-matching lines rather than the matching ones.

And if you specifically want user names only of the form User.Name then you can add this:

lastlog | egrep -v '^qwer|^root$' | egrep -i '^[a-z]*\.[a-z]*'

Upvotes: 3

Related Questions