开发者

BASH: Split MAC Address -> 000E0C7F6676 to 00:0E:0C:7F:66:76

Hy,

Can someone help me with splitting 开发者_开发技巧mac addresses from a log file? :-)

This:

000E0C7F6676

should be:

00:0E:0C:7F:66:76

Atm i split this with OpenOffice but with over 200 MAC Address' this is very boring and slow...

It would be nice if the solution is in bash. :-)

Thanks in advance.


A simple sed script ought to do it.

sed -e 's/[0-9A-F]\{2\}/&:/g' -e 's/:$//' myFile

That'll take a list of mac addresses in myFile, one per line, and insert a ':' after every two hex-digits, and finally remove the last one.


$ mac=000E0C7F6676
$ s=${mac:0:2}
$ for((i=1;i<${#mac};i+=2)); do s=$s:${mac:$i:2}; done
$ echo $s
00:00:E0:C7:F6:67:6


Pure Bash. This snippet

mac='000E0C7F6676'

array=()
for (( CNTR=0; CNTR<${#mac}; CNTR+=2 )); do
  array+=( ${mac:CNTR:2} )
done
IFS=':'
string="${array[*]}"
echo -e "$string"

prints

00:0E:0C:7F:66:76


$ perl -lne 'print join ":", $1 =~ /(..)/g while /\b([\da-f]{12})\b/ig' file.log
00:0E:0C:7F:66:76

If you prefer to save it as a program, use

#! /usr/bin/perl -ln    
print join ":" => $1 =~ /(..)/g
  while /\b([\da-f]{12})\b/ig;

Sample run:

$ ./macs file.log 
00:0E:0C:7F:66:76


imo, regular expressions are the wrong tool for a fixed width string.

perl -alne 'print join(":",unpack("A2A2A2A2A2A2",$_))' filename

Alternatively,
gawk -v FIELDWIDTHS='2 2 2 2 2 2' -v OFS=':' '{$1=$1;print }'

That's a little funky with the assignment to change the behavior of print. Might be more clear to just print $1,$2,$3,$4,$5,$6


Requires Bash version >= 3.2

#!/bin/bash
for i in {1..6}
do
    pattern+='([[:xdigit:]]{2})'
done

saveIFS=$IFS
IFS=':'
while read -r line
do
    [[ $line =~ $pattern ]]
    mac="${BASH_REMATCH[*]:1}"
    echo "$mac"
done < macfile.txt > newfile.txt
IFS=$saveIFS

If your file contains other information besides MAC addresses that you want to preserve, you'll need to modify the regex and possibly move the IFS manipulation inside the loop.

Unfortunately, there's not an equivalent in Bash to sed 's/../&:/' using something like ${mac//??/??:/}.


a='0123456789AB'
m=${a:0:2}:${a:2:2}:${a:4:2}:${a:6:2}:${a:8:2}:${a:10:2}

result:

01:23:45:67:89:AB
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜