scripting grep – How to Use Individual Lines from Grep Outputs

grepscripting

I'm trying to grab lines from grep and sorting them into another command, the command I'm using for grepping atm is as follows (hasn't yet been chopped enough for what I will be using it, but this gives better context):

iwlist wlan0 scanning | grep -oE '(ESSID:|Quality=|Encryption Key:).*'

Output looks like this (but will change depending on my computer's location):

Quality=64/70 Signal Level=-49dBm
Encryption key:on
ESSID:"Hringdu_20558"
Quality=61/70 Signal Level=-48 dBm
Encryption key:on
ESSID:"SiminnEBE932"
Quality=30/70 Signal Level=-71 dBm
Encryption key:on
ESSID:"Siminn106C46
Quality=28/70 Signal Level=-83 dBm
Encryption key:on
ESSID:"SiminnECC63F"

I want to use these lines individually for executing another command

$ssid=$(zenity --list --text "Available Networks" --list --column "ESSID" --column "Secure" --column "Signal" "$ESSID" "$ENC" "$Signal");

These are the begginings of a quickie wireless network selection prompt. $ESSID/$ENC/$Signal would be based on the output from the earlier grep, so what I need to do essentially after working the grep output a bit more to look something like this in the end after chopping it with cut/awk/sed:

91%
on
Hringdu_20558

(note: I get the percentage by multiplying 64 by 10 then dividing by 7; 64*10/7)

Is to apply these lines recursively for every detected ESSID into the zenity command via scripting. And to add to problems; as you may notice the grep output is in reverse order from the zenity command, so this means "Hringdu_20558" would have to go in first, and "87%" would have to go in last.

In other words in this specific scenario I need to somehow grab the third line from the grep output, and append it to the other command, then work up the previous 2 lines, and repeat this going for the third line after the line I started until there are no more lines.

In essence the final zenity command should end up looking something like this based on the above outputs:

$ssid=$(zenity --list --text "Available Networks" --list --column "ESSID" --column "Secure" --column "Signal" "Hringdu_20558" "on" "91%" "SiminnEBE932" "on" "87%" "Siminn106C46" "on" "43%" "SiminnECC63F" "on" "40%");

How can I do this? Can it be done with just basic shell scripting?

Best Answer

I end up with something like this:

ssid=$(iwlist wlan0 scanning |
awk -F: '
BEGIN{ printf "zenity --list --text \"Available Networks\" --list --column ESSID --column Secure --column Signal "; }
/Quality/{ split($0,x,"="); Quality = int(x[2]*100/70+.5); }
/Encryption/{ Encryption = $2; }
/ESSID/{ ESSID = $2;
         printf "%s \"%s\" \"%s%%\" ", ESSID, Encryption, Quality
}' |
sh)

Doesn't really use grep, but it does what you want.

Related Question