Grep Regex for Mac Address

11,814

Solution 1

Try:

grep -io '[0-9a-f]\{12\}' file.txt > macs.txt

Solution 2

((([0-9a-fA-F]{2})[ :-]){5}[0-9a-fA-F]{2})|(([0-9a-fA-F]){6}[
:-]([0-9a-fA-F]){6})|([0-9a-fA-F]{12})

I tested it against following expression that I know for MAC-Adresses. Depending on the syntax of systems, firmwares and applikations.

F3 D3 A4 C1 99 E2
F3:D3:A4:C1:99:E2
F3-D3-A4-C1-99-E2
f3 d3 a4 c1 99 e2
f3:d3:a4:c1:99:e2
f3-d3-a4-c1-99-e2
f3d3a4 c199e2
f3d3a4:c199e2
f3d3a4-c199e2
f3d3a4c199e2
F3D3A4C199E2

Solution 3

One way using sed:

sed -e 's/^.*\([a-fA-F0-9]\{12\}\).*$/\1/' file.txt > macs.txt

Result:

00aa11bb22cc
aa11bb22cc33
Share:
11,814
Alex_Hyzer_Kenoyer
Author by

Alex_Hyzer_Kenoyer

I enjoy Discgolf and a plump Lobster.

Updated on June 17, 2022

Comments

  • Alex_Hyzer_Kenoyer
    Alex_Hyzer_Kenoyer almost 2 years

    I need help with a regex to extract mac addresses from a large file.

    Here is the format of the file:

    Wed Apr 25 10:15:32 EDT 2012 Client: 00aa11bb22cc mac
    Wed Apr 25 10:15:34 EDT 2012 Client: aa11bb22cc33 pc
    

    Here is what I am currently trying with no luck:

    grep -io '[0-9a-f]{12}' file.txt > macs.txt
    

    Any ideas? I just want to extract only the mac address part into the file called macs.txt.

  • Alex_Hyzer_Kenoyer
    Alex_Hyzer_Kenoyer about 12 years
    Damn I knew I was close! haha Thanks a lot, I didn't realize I had to escape the brackets...
  • MattH
    MattH about 12 years
    There's an O'Reilly book (Unix in a nutshell) I always used to refer to for variations in pattern matching between utilities. This particular variation was fresh in my mind
  • Alex_Hyzer_Kenoyer
    Alex_Hyzer_Kenoyer about 12 years
    Thanks, this works great as well. Any idea if this is faster than grep? My log files are fairly large...
  • Birei
    Birei about 12 years
    @Alex_Hyzer_Kenoyer: I don't think so. As far as I know sed is pretty fast but grep usually is a big bet.
  • glenn jackman
    glenn jackman about 12 years
    You can also use the [:xdigit:] character class for which you don't need the -i option: grep -o '[[:xdigit:]]\{12\}'
  • MattH
    MattH about 12 years
    @glennjackman: nice tip, didn't know there was a hexadecimal character class
  • Christian Bongiorno
    Christian Bongiorno almost 12 years
    For completeness sake, you may want to expand the the number group to [0-9a-fA-F]
  • BenT
    BenT over 3 years
    Please provide a description of what this does and how it helps.
  • tink
    tink almost 3 years
    That's a bold statement, actually. If you use your regex against the sample data in Henrik's answer it returns just two lines.
  • Freedo
    Freedo over 2 years
    how to use this with a pipe ? like cat txt | grep mac
  • user unknown
    user unknown over 2 years
    Did you try `cat txt | egrep -io '[0-9a-f]{12}'? Where is the problem?