awk escape plus '+' sign

Viewed 43

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?

2 Answers

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

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'
Related