Drewber49er
Drewber49er

Reputation: 3

Passing dynamic regexp via bash shell script

I'm coding a simple bash script to pass a IP port to a regexp to an awk command. I'm looking for the port only in the Local Destination

Here is the code:

#!/bin/bash
s=$1
port="/[^0-9]$s$/"
netstat -numeric | awk -v pat="$port" '$6 == "ESTABLISHED" && $4 ~ pat {print}'

Here is example of data.

tcp        0      0  1.9.1.1:23    1.9.2.1:54156 ESTABLISHED
tcp        0      0  1.9.1.1:23    1.9.2.4:51376 ESTABLISHED
tcp        0      0  1.9.1.1:23    1.9.2.1:53299 ESTABLISHED
tcp        0      0  1.9.1.1:23    1.9.2.1:64695 ESTABLISHED
tcp        0      0  1.9.1.1:53086 1.9.1.8:23   ESTABLISHED
tcp        0      0  1.9.1.1:23    1.9.2.1:53296 ESTABLISHED

When I run the script, it returns nothing.

When I run it manually , it returns the following:

netstat -numeric | awk '$6 == "ESTABLISHED" && $4 ~ /[^0-9]23$/ {print}'

tcp        0      0  1.9.1.1:23    1.9.2.1:54156 ESTABLISHED
tcp        0      0  1.9.1.1:23    1.9.2.4:51376 ESTABLISHED
tcp        0      0  1.9.1.1:23    1.9.2.1:53299 ESTABLISHED
tcp        0      0  1.9.1.1:23    1.9.2.1:64695 ESTABLISHED
tcp        0      0  1.9.1.1:23    1.9.2.1:53296 ESTABLISHED

Any suggestions would greatly appreciated.

Upvotes: 0

Views: 462

Answers (1)

Ed Morton
Ed Morton

Reputation: 204310

port="[^0-9]$s$"

You can remove the {print}, btw, as that's the default action, so all you need is:

s=$1
port="[^0-9]$s$"
netstat -numeric | awk -v pat="$port" '$6 == "ESTABLISHED" && $4 ~ pat'

The reason what you had didn't work is that /.../ are regexp constant delimiters, like "..." are string constant delimiters so including them in a dynamic regexp would be like if you included the quotes in a string, e.g. foo="\"stuff\"" instead of foo="stuff", the "/"s become part of the regexp instead of delimiters for the regexp.

Upvotes: 4

Related Questions