Bash:awk从数组项中删除括号

时间:2017-12-31 14:39:19

标签: bash awk grep format ip

所以我正在创建一个小型网络扫描自动化工具,使用nmap作为后端的一部分,当试图获取主机名和IP地址时,IP的格式如下“(192.168.0.1)”目前我正在使用这个位获取主机名和IP并打印的代码。

devices=($( nmap $net_addr -sn | grep -E '([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})' | awk {' print $5 "\t" $6)'} ))

printf '%-10s %s\n' "${devices[@]}"

此代码将打印此

UNKNOWN (192.168.0.1)
UNKNOWN (192.168.0.3)
UNKNOWN (192.168.0.5)
UNKNOWN (192.168.0.6)
UNKNOWN (192.168.0.16)
UNKNOWN (192.168.0.18)
UNKNOWN (192.168.0.19)
UNKNOWN (192.168.0.21)
UNKNOWN (192.168.0.22)
UNKNOWN (192.168.0.23)
UNKNOWN (192.168.0.32)
UNKNOWN (192.168.0.253)

我试图使用substr($ 6,2),但这只能扼杀第一位,遗憾的是nmap IP地址长度可变,这对我没有帮助。 简而言之,这是理想的输出。

UNKNOWN 192.168.0.1
UNKNOWN 192.168.0.3
UNKNOWN 192.168.0.5
UNKNOWN 192.168.0.6
UNKNOWN 192.168.0.16
UNKNOWN 192.168.0.18
UNKNOWN 192.168.0.19
UNKNOWN 192.168.0.21
UNKNOWN 192.168.0.22
UNKNOWN 192.168.0.23
UNKNOWN 192.168.0.32
UNKNOWN 192.168.0.253

这是nmap 192.168.0.0/24 -sn

的输出
Starting Nmap 7.40 ( https://nmap.org ) at 2017-12-31 14:42 UTC
Nmap scan report for UNKNOWN (192.168.0.1)
Host is up (0.0014s latency).
Nmap scan report for UNKNOWN (192.168.0.3)
Host is up (0.052s latency).
Nmap scan report for UNKNOWN (192.168.0.5)
Host is up (0.0065s latency).
Nmap scan report for UNKNOWN (192.168.0.6)
Host is up (0.0073s latency).
Nmap scan report for UNKNOWN (192.168.0.7)
Host is up (0.029s latency).
Nmap scan report for UNKNOWN (192.168.0.16)
Host is up (0.011s latency).
Nmap scan report for UNKNOWN (192.168.0.18)
Host is up (0.053s latency).
Nmap scan report for UNKNOWN (192.168.0.21)
Host is up (0.011s latency).
Nmap scan report for UNKNOWN (192.168.0.22)
Host is up (0.012s latency).
Nmap scan report for UNKNOWN (192.168.0.23)
Host is up (0.0061s latency).
Nmap scan report for UNKNOWN (192.168.0.32)
Host is up (0.0013s latency).
Nmap scan report for UNKNOWN (192.168.0.253)
Host is up (0.0011s latency).
Nmap done: 256 IP addresses (12 hosts up) scanned in 3.16 seconds

2 个答案:

答案 0 :(得分:1)

根据您显示的输入,您可以尝试使用单个awk来获得显示的预期输出。

your_command | awk '/Nmap scan report/{gsub(/\)|\(/,"",$NF);print $(NF-1),$NF}' 

编辑: 从OP的命令中删除grep并尝试在单awk内解决它。

devices=$(nmap $net_addr -sn | awk --re-interval '{if(match($0,/\([0-9]{3}\.[0-9]{3}\.[0-9]{1,3}\.[0-9]{1,3}\)/)){gsub(/\)|\(/,"",$NF);print $(NF-1),$NF}}')

此外,由于我的awk是旧版本,以防你有最新版本的awk,所以请不要在解决方案中使用--re-interval

答案 1 :(得分:1)

你也可以试试这个sed

nmap $net_addr -sn | sed '/^Nmap scan report for /!d;s///;s/[)(]//g'