2

I have mac addresses in this shape "001122334455" that I want to turn into "00 11 22 33 44 55". I guess there is a way to do this in one line, but the only way I found is the following ridiculously horrible proc. Can someone show me how to do this properly ?

proc addSpaces { mac } {
    set mac [split $mac {}]                                  
    set i 0                                                  
    while { $i < 12 } {                                      
        if { [expr $i % 2] == 0 } {                          
            append macAddr " "                               
            append macAddr [lindex $mac $i]                  
            append macAddr [lindex $mac [expr $i + 1]]       
        }                                                    
        incr i                                               
    }
    return $macAddr                                                        
}
little-dude
  • 1,544
  • 2
  • 17
  • 33

2 Answers2

4

You can use tcl's incredibly flexible foreach:

foreach {a b} [split $mac {}] {
    append macAddr " $a$b"
}

Or if you want to get rid of the leading space, construct a list instead of a string:

foreach {a b} [split $mac {}] {
    lappend macAddr "$a$b"
}
join $macAddr " "

Alternatively you can just string trim your string before returning

slebetman
  • 109,858
  • 19
  • 140
  • 171
4

regsub also works

set s 001122334455
set t [string trimright [regsub -all {..} $s {& }]]
puts ">$t<"
>00 11 22 33 44 55<

@Donal's suggestion is great:

set t [join [regexp -all -inline .. $s]]  ;# "00 11 22 33 44 55"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352