735Tesla
735Tesla

Reputation: 3241

Grep Regex Not Behaving as Expected

I have the following file:

this:that
thisthat
this that
this:
:that
aa:bb
13a:59b
a4:b6
thisentryistoolongtomatchthepattern:1234567abcderfslsfl
4df)#(*:049

I would like to match only these entries:

this:that
aa:bb
13a:59b
a4:b6

I am trying to grep out just the entries containing [less than 10 alphanumeric characters]:[less than 10 alphanumeric characters]. I tried the following expression: ^[A-z0-9]{0,10}:[A-z0-9]{0,10}$. However, this does not match anything. Is there something in this expression not supported by grep?

Upvotes: 1

Views: 82

Answers (4)

Scrutinizer
Scrutinizer

Reputation: 9926

Just use grep -E and I would replace the ranges with [[:alnum:]], so you cannot run into trouble because of locale. Also I think you would be looking for 1, instead of 0,

grep -E '^[[:alnum:]]{1,10}:[[:alnum:]]{1,10}$' file

or

grep '^[[:alnum:]]\{1,10\}:[[:alnum:]]\{1,10\}$' file

Upvotes: 0

SQB
SQB

Reputation: 4078

^[A-Za-z0-9]\{1,10\}:[A-Za-z0-9]\{1,10\}$
  • You'll want to escape the braces, otherwise they'll match actual braces. This is why you got nothing.

  • As I noted in my comment, I assume you want at least one character on either side of the colon, so I adjusted accordingly.

  • To avoid matching non-alphanumerical characters that live between Z and a, I changed the definition of the character class.

Upvotes: 2

aelor
aelor

Reputation: 11116

just modified your regex a bit, hope this helps

\b[A-z0-9]{1,10}:[A-z0-9]{1,10}/g

according to your regex ^ will assume position at start of your matching string i.e. before "this:that" and $ will take a position at the end of the whole string i.e. after 4df)#(*:049

http://regex101.com/r/rN7hQ2

Upvotes: 1

Toto
Toto

Reputation: 91385

How about:

grep -P '^[A-z0-9]{0,10}:[A-z0-9]{0,10}$' in.txt

output:

this:that
this:
:that
aa:bb
13a:59b
a4:b6

If you don't want this: nor :that, change {0,10} to {1,10}.

Also, you should use [a-zA-Z0-9] instead of [A-z0-9]

Upvotes: 1

Related Questions