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
Comments
-
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 about 12 yearsDamn I knew I was close! haha Thanks a lot, I didn't realize I had to escape the brackets...
-
MattH about 12 yearsThere'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 about 12 yearsThanks, this works great as well. Any idea if this is faster than grep? My log files are fairly large...
-
Birei about 12 years@Alex_Hyzer_Kenoyer: I don't think so. As far as I know
sed
is pretty fast butgrep
usually is a big bet. -
glenn jackman about 12 yearsYou can also use the
[:xdigit:]
character class for which you don't need the-i
option:grep -o '[[:xdigit:]]\{12\}'
-
MattH about 12 years@glennjackman: nice tip, didn't know there was a hexadecimal character class
-
Christian Bongiorno almost 12 yearsFor completeness sake, you may want to expand the the number group to [0-9a-fA-F]
-
BenT over 3 yearsPlease provide a description of what this does and how it helps.
-
tink almost 3 yearsThat's a bold statement, actually. If you use your regex against the sample data in Henrik's answer it returns just two lines.
-
Freedo over 2 yearshow to use this with a pipe ? like cat txt | grep mac
-
user unknown over 2 yearsDid you try `cat txt | egrep -io '[0-9a-f]{12}'? Where is the problem?