-3

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?

12
  • 1
    * matches zero or more occurrences, try with + Commented Sep 28, 2015 at 11:45
  • 1
    The mistake you are making is posting a command, without example input that doesn't work with the solution you have (which you provided) and also leaving out the output that you are getting based on that input and the command. Please update your post with that information, and suppress any urge to include EDIT/UPDATE in the text when you do so. It is also quite a good idea to read at least the help->tour
    – Anthon
    Commented Sep 28, 2015 at 11:55
  • @Anthon I have included valid and invalid cases
    – Mathew
    Commented Sep 28, 2015 at 12:44
  • 2
    what's wrong with what you've got? is your problem that you're also turning up blank lines? if so, just do what @don_crissti suggests. else, I can't see how it would fail... unless you also want to handle lines with an odd number of characters, in which case you need to add .? just before the $. You might also drop ^ and $ and use -x.
    – mikeserv
    Commented Sep 28, 2015 at 12:51
  • What Anthon and mikeserv said; in case you don't want odd characters to be numbers, egrep '^([^0-9][0-9])+$' file.txt
    – kos
    Commented Sep 28, 2015 at 13:08

1 Answer 1

0

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
1
  • thanks for the detailed answer, what would i need to do if i want to include empty line and single characters ?(not part of question, was just curious)
    – Mathew
    Commented Sep 28, 2015 at 18:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .