Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 2067  / 3 Years ago, sat, june 12, 2021, 6:25:33

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.


More From » grep

 Answers
0

AWK is very powerful and perfect for this. Basically, you want to:




  1. Save the address in the address line

  2. If the ESSID matches your value, print it



The shortest version I could think of:



sudo iwlist wlan0 scan|awk '/Address:/{a=$5}/ESSID:"name"/{print a}'


/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:




  1. If a line matches Address:, the fifth field is stored in a variable named a. Fields are whitepace-delimited lines.

  2. If a line matches ESSID:"name", variable a 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


[#40742] Monday, June 14, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cklaceowne

Total Points: 228
Total Questions: 102
Total Answers: 111

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
;