Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude regex bash script

Tags:

regex

grep

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]'
like image 864
ibash Avatar asked Mar 23 '12 16:03

ibash


2 Answers

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.

like image 52
cha0site Avatar answered Oct 22 '22 11:10

cha0site


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]*'
like image 25
Lee Netherton Avatar answered Oct 22 '22 10:10

Lee Netherton