In Ubuntu, with command ifconfig -a, I obtain all the information about my ethernet/wifi interfaces.
But I need to obtain as output only the MAC address, like:
ab:cd:ef:12:34:56
57:89:12:34:ac:23
12:34:56:ab:cd:efHow can I obtain this?
5 Answers
You can access the address file for each device on the /sys virtual filesystem. The MAC address should be in /sys/class/net/<device-name>/address:
$ cat /sys/class/net/enp1s0/address
34:17:eb:5d:88:7cFor all devices:
$ cat /sys/class/net/*/address
34:17:eb:5d:88:7c
00:00:00:00:00:00
64:5a:04:69:50:45 7 The easiest way would be to use grep with PCRE:
$ ifconfig -a | grep -Po 'HWaddr \K.*$'
74:d4:35:84:34:13 grep -Pwill enable us to useperlcompatible Regexgrep -owill only take the matched portion of the lineWe have matched
HWaddrbefore our desired match (MAC addresses) and then discardHWaddrby\Kto print only the MAC addresses.
@Helio has mentioned an important point, this is highly dependent on your language i.e. locale settings. To overcome that you can use the C locale (uses ASCII character set) for this command only:
$ LANG=C ifconfig -a | grep -Po 'HWaddr \K.*$'
74:d4:35:84:34:13 8 Here are a few ways:
grep. There are various regular expressions that will pick these up. Here, I am looking for 5 repetitions of 2 letters or numbers followed by a colon, then any two characters. The-imakes the match case insensitive and the-omakesgrepprint only the matched portion.-Eenables extended regular expressions. The same regex also works with PCREs (-P).ifconfig -a | grep -ioE '([a-z0-9]{2}:){5}..'sed. The-nsuppresses normal output and the-renables extended regular expressions. Using the same regex as above, this script will attempt to replace everything on the line with the part of it that matches the regex. If the substitution was successful, the resulting line is printed (because of thepat the end of the substitution).ifconfig -a | sed -rn 's/.*(([a-z0-9]{2}:){5}..).*/\1/p'awk. If the line starts with a word character ([a-zA-Z0-9_]), and has 5 fields, print the last one.ifconfig -a | awk '/^\w/&&NF==5{print $NF}'Perl, where, as usual, there are more than one ways to do it. This one is the same logic as the
awkabove. The-atells perl to split each input line into the@Farray.ifconfig -a | perl -lane 'if(/^\w/&&$#F==4){print $F[$#F]}'Alternatively, you can use the regex from the previous approaches:
ifconfig -a | perl -lne '/(([a-z0-9]{2}:){5}..)/ && print $1'Coreutils.
LANG_ALL=C ifconfig -a | grep 'HWadd' | tr -s ' ' '\t' | cut -f 5
As some have commented, ifconfig is deprecated in favor of the ip command. So combining the various solutions and comments, I'd use:
$ LANG=C ip link show | awk '/link\/ether/ {print $2}'
FF:FF:FF:FF:FF:FF ifconfig -a | grep HWaddr | awk '{print $5}'
If your system output is non-English in this command, then it makes sense to run it this way.
LANG=C ifconfig -a | grep HWaddr | awk '{print $5}'
This is applicable to all solutions.
7