I run the following command:
sudo iwlist eth0 scan
and get output that looks like this:
Cell 01 - Address: AB:CD:EF:12:34:56
ESSID:"name"
Protocol:IEEE 802.11g
Mode:master
Frequency:2.417 GHz (Channel 2)
Encryption key:on
I won't bother filling it all out, as I'm trying to fix a laptop and I cannot simply copy the output.
How can I use built-in tools such as grep
, awk
, sed
, etc. to fetch information given certain criteria? For example:
I want to grab the mac address when knowing the essid. I also don't want to rely on the Cell #
or line positions. Knowing common information, like the word Address before the mac is fine.
Expected output:
AB:CD:EF:12:34:56
I want to use it in a variable, like so:
sudo iwconfig eth1 ap $(command)
Where command would result in the expected result. If there's another way of pushing the result as a variable using >
or something, that works as well. (command > sudo iwconfig eth1 ap $1
)
Thanks.
My personal preference for these things is pure bash. The script below should do what you are looking for.
After pasting the above into your terminal, you should be able to run
get_mac_of_essid name
to get the MAC address associated with network "name" as many times as needed.I suggest learning the
cut
command. It makes this task easy. Forgive theecho
, but I wanted to demonstrate on the original data.AWK is very powerful and perfect for this. Basically, you want to:
The shortest version I could think of:
/pattern/
is a regular expression that is compared with input. If it matches, the part after the curly brackets ({...}
) is executed.The
awk
command processes input line by line:Address:
, the fifth field is stored in a variable nameda
. Fields are whitepace-delimited lines.ESSID:"name"
, variablea
is printed (the last address that matched).Both rules are executed, but 1 comes before 2 so
a
is always set.Manual page for awk