Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SED to format MAC address

Status
Not open for further replies.

rizacer

Technical User
Apr 3, 2004
16
US
I am trying to find a script that will format a MAC address from say

001122334455 to 00:11:22:33:44:55

I found a post from a while back that used SED to do something similar however it only formats correctly if I used echo or a single line in the source file

Here is what im using as a reference:
=================================

sed 's!\-!!g;s!\.!!g;s!\(..\)!\1:!g;s!:$!!' /home/ntop/MAC.txt
00:26:0B:5C:AF:7A:
00:26:0B:5C:B0:67:
00:26:0B:5C:AD:5E:
00:26:0B:5C:B7:5F:
00:26:0B:5C:E2:97:
00:26:0B:5C:AD:21:
00:26:0B:5C:AD:F7:
00:26:0B:5C:AE:5C

=================

only the last MAC gets the final colon stripped out. If I use echo or a single line it works fine

==================
root@Netflow:~# echo 121234345656 | sed 's!\.!!g;s!\(..\)!\1:!g;s!:$!!'
12:12:34:34:56:56

===================


scripting is completely new to me so if there is something better then sed like php,etc I have no problems using that

Any pointers are appreciated!!

Thanks
-DP
 
I'd use awk and its substr builtin function.

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
What's the output of cat -vet /home/ntop/MAC.txt? I suspect you have some extra characters on the ends of the lines (except the last one) which are preventing that sed script from working as intended. Possibly either a space, or possibly the file is actually in Windows/DOS format with CR/LF line terminators.

Annihilannic.
 
Ah very interesting that was something that didnt cross my mind

root@Netflow:~# cat -vet /home/ntop/MAC.txt
00260B5CAF7A^M$
00260B5CB067^M$
00260B5CAD5E^M$
00260B5CB75F^M$
00260B5CE297^M$
00260B5CAD21^M$
00260B5CADF7^M$
00260B5CAE5C$
$

The source file was a copy from an M$ excel file to a txt file
 
Yep, the ^Ms are your problem. Either dos2unix the file first, or modify your sed script to remove those too, e.g.

Code:
sed '[red]s!^M$!!;[/red]s!\-!!g;s!\.!!g;s!\(..\)!\1:!g;s!:$!!' /home/ntop/MAC.txt

To insert the Control-M character in vi, you would use Ctrl-V Ctrl-M.

Annihilannic.
 
The additions to the script didn't seem to make a difference. however dos2unix worked like a charm! Thanks for the help with it all.

-DP
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top