I am trying to write a Linux command using egrep
that validates lines whose even character is a number.
I am doing it this way:
egrep "^(.[0-9])*$" text.txt
However, this fails for i) empty lines and ii) cases where the number of characters is odd. It should match 123
since the only odd position is indeed a number, but it doesn't.
Valid patterns:
a2b4c6
000000
123
a1b
a1b2c3q
Invalid patterns:
aaaa
0a0a0a
a1bq
Could anyone please tell me what mistake I am making?
EDIT: The only restriction is that every alternate character needs to be even; the length of the entire line might be even or odd. The command above only allows even length ex: 1234,a1b2c3 etc but even 123,a1b are valid but this doesn't match them. My question is: How to handle this?
Your regular expression will match empty lines because *
means "zero or more" so ^(.[0-9])*$
matches on an empty line. You can fix that by using +
("match 1 or more") instead.
Your next problem is that you don't match if the number of characters on a line is even. To avoid that, you can tell grep
to also allow 0 or 1 character at the very end:
grep -E "^(.[0-9])+.?$"
For example:
$ cat file
a2b4c6
000000
123
aaaa
0a0a0a
$ grep -E "^(.[0-9])+.?$" file
a2b4c6
000000
123
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments