BASH: Split MAC Address & # 8594; 000E0C7F6676-00: 0E: 0C: 7F: 66: 76

Hy

Can someone help me with splitting MAC addresses from a log file? :-)

It:

000E0C7F6676 

it should be:

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

Atm I split this into OpenOffice, but with over 200 MAC addresses, "this is very boring and slow ...

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

Thanks in advance.

+4
source share
6 answers

A simple sed script should do this.

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

This will take the list of MAC addresses in myFile , one on each line and insert ':' after every two hexadecimal digits and finally delete the last one.

+5
source
 $ 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 
+5
source

Clean 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 
+4
source
  $ 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; 

Run Example:

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

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

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

On the other hand,
gawk -v FIELDWIDTHS='2 2 2 2 2 2' -v OFS=':' '{$1=$1;print }'

This is a little ridiculous with the task of changing print behavior. It might be more clear to just print $ 1, $ 2, $ 3, $ 4, $ 5, $ 6

+1
source

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 information other than the MAC addresses that you want to save, you need to change the regular expression and possibly move the IFS manipulation inside the loop.

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

+1
source

Source: https://habr.com/ru/post/1315932/


All Articles