Bash:awk从数组项中删除括号
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Bash:awk从数组项中删除括号相关的知识,希望对你有一定的参考价值。
所以我正在创建一个小型网络扫描自动化工具,使用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 " " $6)'} ))
printf '%-10s %s
' "${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
答案
根据您显示的输入,您可以尝试使用单个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
。
另一答案
你也可以试试这个sed
nmap $net_addr -sn | sed '/^Nmap scan report for /!d;s///;s/[)(]//g'
以上是关于Bash:awk从数组项中删除括号的主要内容,如果未能解决你的问题,请参考以下文章