Skip to content
shellhacks.dev
Text Processing

Match a MAC Address with grep -E in Bash

Match a MAC address with grep -E as six hex pairs joined by colons, anchored at both ends. Without anchors a longer address still matches its first six pairs.

2 min read
Summarize in AI

You need to pick MAC addresses out of a file or check that a string has the right shape.

Shell
printf '%s\n' aa:bb:cc:dd:ee:ff AA:BB:CC:DD:EE:FF aa:bb:cc:dd:ee aa:bb:cc:dd:ee:gg aa-bb-cc-dd-ee-ff > macs.txt
grep -E '^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$' macs.txt
echo "--- colon or dash"
grep -E '^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$' macs.txt
echo "--- without anchors"
echo 'seven octets aa:bb:cc:dd:ee:ff:00' | grep -oE '([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}'
Text
aa:bb:cc:dd:ee:ff
AA:BB:CC:DD:EE:FF
--- colon or dash
aa:bb:cc:dd:ee:ff
AA:BB:CC:DD:EE:FF
aa-bb-cc-dd-ee-ff
--- without anchors
aa:bb:cc:dd:ee:ff

Each pair is two hex digits, and ([0-9A-Fa-f]{2}:){5} repeats a pair with its colon five times before the last pair with no colon. Anchoring with ^ and $ rejects the five-pair line and the one with gg. The class [:-] accepts colons and dashes, which let aa-bb-cc-dd-ee-ff through. The unanchored run in the last part shows the danger: a seven-pair string still yields its first six pairs. See Regular Expressions in POSIX.

The pattern checks the shape only, and it allows a colon pair followed by a dash pair in the same address. Dotted forms such as aabb.ccdd.eeff and addresses without separators need other patterns. It does not tell you whether the address is real, unicast or locally administered.

Share

More snippets

Text Processing

Replace Only the Nth Match on a Line with sed

Replace only the second or a later match on a line with a numeric flag on the s command, and add g to replace from that match onward. The count restarts on every line.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.