I need to grep for a ip address, and then find a specific line that precedes the ip address and print that line only
I ran the netsh and store in SSID.txt
SSID.txt
SSID1:TESTWIFI_1
BSSID1:1.1.1.1
SSID2:TESTWIFI_2
BSSID1:2.2.2.2
BSSID2:3.3.3.3
BSSID3:4.4.4.4
I want to grep 4.4.4.4
grep '4.4.4.4' SSID.txt | cut -d: -f2-
And then find the first instance of SSID before the ip address.
I know how to print a specific number of lines after using grep but I don't want to do that because there are an inconsistent amount of BSSIDS under each SSID
grep -A[] or -B [num]
Desired Output
4.4.4.4 - SSID2:TESTWIFI_2
Could you please try following, this should be an easy task for awk
program.
awk 'BEGIN{FS=":";OFS=" - "} /^SSID[0-9]/{val=$0;next} /4\.4\.4\.4/ && val{print $2,val}' Input_file
Adding a non-one liner form of above code now:
awk '
BEGIN{
FS=":"
OFS=" - "
}
/^SSID[0-9]/{
val=$0
next
}
/4\.4\.4\.4/ && val{
print $2,val
}
' Input_file
Explanation: Adding explanation of above code.
awk ' ##Starting awk program here.
BEGIN{ ##Starting BEGIN section here for program.
FS=":" ##Setting FS field separator as : colon here.
OFS=" - " ##Setting output field separator as space - space for all lines.
} ##Closing BEGIN section of this program here.
/^SSID[0-9]/{ ##Checking condition if any line starts from SSIDand digit then do following.
val=$0 ##Creating variable val whose value is current line value.
next ##next will skip all further statements from here.
}
/4\.4\.4\.4/ && val{ ##Checking condition if a line has 4.4.4.4 escaping DOT here to take it as literal character and checking condition if val is NOT NULL.
print $2,val ##Printing $2 of current line and variable val here.
}
' Input_file ##Mentioning Input_file name here.
Another approach:-
awk -v S="4.4.4.4" '/^SSID/{v=$0;next}$0~S{print S " - " v}' SSID.txt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.