我有以下格式的数据列表:
eth0: flags=73<UP,LOOPBACK,RUNNING> mtu 1500
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0xfe<compat,link,site,host>
loop (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
eth1: flags=73<UP,LOOPBACK,RUNNING> mtu 1500
inet6 ::1 prefixlen 128 scopeid 0xfe<compat,link,site,host>
loop (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
我需要选择eth1
(这是第一个单词,并且该单词始终以e
开头)之后没有127.0.0.1
(也可能会在后面出现)下一行)。
此处eth0
不合格,因为其后跟127.0.0.1
我尝试了一切,但似乎没有任何效果。正则表达式甚至可能吗?如果是,那怎么办?
答案 0 :(得分:2)
您可以使用此awk
命令,该命令在Ununtu上本机可用:
awk -F ': ' '$1 ~ /^e[[:alnum:]]+$/ && NF==2{s=$1; p=NR}
NR==p+1 && !/ 127\.0\.0\.1[[:blank:]]/{print s}'
说明:
-F ': ' # make ": " as input delimiter
$1 ~ /^e[[:alnum:]]+$/ && NF==2 { # if $1 starts with e and has 1+ alphanumeric characters later and there are exactly 2 fields in that line
s=$1 # save $1 in var s
p=NR # save record no in var p
}
NR==p+1 && !/ 127\.0\.0\.1[[:blank:]]/ { # we are processing (p+1)th record and it doesn't have " 127.0.0.1 " in it
print s # print s
}
答案 1 :(得分:2)
$ awk -v RS= -F':' '!/[[:space:]]127\.0\.0\.1[[:space:]]/{print $1}' file
eth1
在每个UNIX机器上的任何外壳中使用任何POSIX awk都可以使用。
答案 2 :(得分:1)
不确定Ubuntu的实现细节,但可以使用否定的前瞻:
^eth\d+(?=:)(?!.*\n.*[^0-9]127\.0\.0\.1[^0-9])
^eth\d+(?=:)
-行的开头必须是“ eth”,后跟一个或多个数字,然后是冒号,但不要捕获冒号(?!.*\n.*[^0-9]127\.0\.0\.1[^0-9])
-确保上一个匹配项之后的内容不包含“ 127.0.0.1”