1

So i spent like 2H for research, but cant get it working

I want to awk display 4 lines containing my var

stored.txt content is like:

DATE: 12.12.1222  
BSSID: 22:33:44:55:66:88  
SSID: TestAP1  
PIN: 29483029  
PSK: SAHJSHGD  

DATE: 12.12.1222  
BSSID: 11:22:33:44:55:66  
SSID: TestAP12  
PIN: 12345678  
PSK: ABCDEFG

I tried:

cat stored.txt | awk -v var="11:22:33:44:55:66" '/BSSID: /{print var} {p = 4} p > 0 {print $0; p--}

I don't know how to put awk variable inside this.

Needed output:

BSSID: 11:22:33:44:55:66  
SSID: TestAP12  
PIN: 12345678  
PSK: ABCDEFG  
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 3
    @EdMorton, are you sure that's an appropriate duplicate target? The OP here already knows about `-v`. – Charles Duffy Aug 06 '22 at 18:01
  • @CharlesDuffy The accepted answer in the question I duped, under "Example of testing the contents of a shell variable as a regexp:", shows how to solve the problem of "Using awk variable inside slashes" as the OP is asking in the subject so it seems reasonable to me but feel free to re-open it if you disagree. On re-reading the question I could go either way. – Ed Morton Aug 06 '22 at 18:10
  • 1
    I think that comment suffices, by giving someone a hint where to look to find the relevant part of the linked duplicate's answer. – Charles Duffy Aug 06 '22 at 18:14

2 Answers2

2

You don't need the slashes at all. Just check whether $2 == var when $1 == "BSSID:".

awk -v var="11:22:33:44:55:66" '
  $1 == "BSSID:" && $2 == var {p = 4}
  p > 0                       {print $0; p--}
' <stored.txt

See this running in an online sandbox at https://replit.com/@CharlesDuffy2/WiseTreasuredDirectories#main.sh


That said, if you really do want a regex match against $0 (which is what the slashes do), you can accomplish that with content from a variable using the ~ operator:

awk -v var="11:22:33:44:55:66" '
  $0 ~ ("BSSID: " var) {p = 4}
  p > 0                {print $0; p--}
' <stored.txt
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

A variation on OP's awk:

$ awk -v var="11:22:33:44:55:66" '$1~"BSSID:" && $2==var {p=4} p-->0' stored.txt
BSSID: 11:22:33:44:55:66
SSID: TestAP12
PIN: 12345678
PSK: ABCDEFG

A grep approach:

$ var='11:22:33:44:55:66'
$ grep -A3 "BSSID: ${var}" stored.txt
BSSID: 11:22:33:44:55:66
SSID: TestAP12
PIN: 12345678
PSK: ABCDEFG
markp-fuso
  • 28,790
  • 4
  • 16
  • 36