2

Trying to find matching lines from 'wg' (wireguard) command output where public_keys are given which can have forward slash and/or '+' (plus) signs.

So I try: awk '$0~v' v="$peer" RS=

# peer="KDyRQuyvygoAamIMB/6RKWxyb7urysDCldIVbIM5DRQ="
# echo $peer
KDyRQuyvygoAamIMB/6RKWxyb7urysDCldIVbIM5DRQ=
# wg | awk '$0~v' v="$peer" RS=
peer: KDyRQuyvygoAamIMB/6RKWxyb7urysDCldIVbIM5DRQ=
  preshared key: (hidden)
  endpoint: 1.2.3.4:44529
  allowed ips: 10.33.17.0/24
  latest handshake: 41 seconds ago
  transfer: 3.64 KiB received, 7.43 KiB sent
  persistent keepalive: every 25 seconds

While the above works with forward slashes, the following does not work if public_keys/strings contain plus '+' sign:

# peer="JeMdiPUksJRpc+LNGbG9Nw/ubVSzj/eFGgrEVwp0z2w="
# echo $peer
JeMdiPUksJRpc+LNGbG9Nw/ubVSzj/eFGgrEVwp0z2w=
# wg | awk '$0~v' v="$peer" RS=
#

How would a match work in this situation?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Christoph Lösch
  • 645
  • 7
  • 22
  • 3
    BTW, `echo $peer` is itself buggy -- it should always be `echo "$peer"`. See [I just assigned a variable, but `echo $variable` shows something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Aug 22 '22 at 20:43

2 Answers2

1

Don't use regex match, use plain string search using index using any one of following options:

# if $peer needs to be matched at the start position of 2nd field
wg | awk -v v="$peer" -v RS= '$1=="peer:" && index($2, v) == 1'

# or if $peer needs to be full matched with 2nd field
wg | awk -v v="$peer" -v RS= '$1=="peer:" $2 == v'

This would match value of $peer at the start of $2 when $1 is peer:.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • `jot -w 'peer: %9lX' - 47153691294923 47153691294923 | mawk -v ___='2AE2D304FCCB' -v RS= -- 'END { print NR,NF, $0 } $1=="peer:" $2 == ___ { print "matched" } ' 1 2 peer: 2AE2D304FCCB` :: `nawk: syntax error at source line 1 context is END { print NR,NF, $0 } $1=="peer:" $2 >>> == <<< nawk: bailing out at source line 1` ::: `gawk -v ___='2AE2D304FCCB' -v RS= 'END { print NR,NF, $0 } $1=="peer:" $2 == ___ { print "matched" } ' gawk: cmd. line:1: END { print NR,NF, $0 } $1=="peer:" $2 == ___ { print "matched" } gawk: cmd. line:1: ^ syntax error` – RARE Kpop Manifesto Aug 29 '22 at 04:12
  • long story short - `gawk` and `nawk` both failed out, while `mawk` quietly accepted it but failed to match it. – RARE Kpop Manifesto Aug 29 '22 at 04:13
0

To do this robustly avoiding false matches with regexp metachars or substrings you should use full string matching on lines:

wg | awk -v v="$peer" '$0 == ("peer: " v){f=1} f'

or fields:

wg | awk -v v="$peer" -v RS= '$2 == v'
Ed Morton
  • 188,023
  • 17
  • 78
  • 185