[Durham] Meeting reminder: Tuesday 15th, 19:30, Durham rowing club.

Martin Ward martin at gkc.org.uk
Fri Jan 11 14:17:17 UTC 2013


On Friday 11 Jan 2013 at 13:04, Dougie Nisbet <dougie at highmoor.co.uk> wrote:
> And for homework ...
> 
> looking for a bash code snippet that will take a MAC address in any of
> the formats:
> 
> cccc.cccc.cccc
> cc:cc:cc:cc:cc:cc
> cccccccccccc
> 
> recognize it and convert it if necessary to cccc.cccc.cccc
> 
> Error if invalid format.

There is also the format: cc-cc-cc-cc-cc-cc

perl solution:

for (@ARGV) {
  if (/^(([[:xdigit:]]{4}(\.|$)){3}
        |([[:xdigit:]]{2}(:|-|$)){6}
        |[[:xdigit:]]{12})$/x) {
    s/[\.:-]//g;
    s/(....)(?=.)/$1./g;
    print "$_\n";
  } else {
    warn "Invalid format: $_\n";
  }
}

Note: the above code will truncate an extra trailing delimiter.
If you don't want this, then change the delimiter tests:

for (@ARGV) {
  if (/^(([[:xdigit:]]{4}(\.(?=.)|$)){3}
        |([[:xdigit:]]{2}((:|-)(?=.)|$)){6}
        |[[:xdigit:]]{12})$/x) {
    s/[\.:-]//g;
    s/(....)(?=.)/$1./g;
    print "$_\n";
  } else {
    warn "Invalid format: $_\n";
  }
}

I am not sufficiently familiar with bash's regular expression
syntax to translate. Does bash have zero-width lookahead assertions?

-- 
			Martin

STRL Reader in Software Engineering and Royal Society Industry Fellow
martin at gkc.org.uk  http://www.cse.dmu.ac.uk/~mward/  Erdos number: 4
G.K.Chesterton web site: http://www.cse.dmu.ac.uk/~mward/gkc/
Mirrors:  http://www.gkc.org.uk  and  http://www.gkc.org.uk/gkc



More information about the Durham mailing list