问题描述
我试过 this suggestion :
ip -o -f inet addr show | awk '/scope global/ {print $4}'
但是输出带有子网掩码的 IP 地址:
192.168.1.108/24
我只想要数字 24
解决方法
ip addr show
可以输出 JSON 数据,因此可以使用 jq
进行可靠的显式解析:
ip \
-family inet \
-json \
addr show |
jq -r '.[].addr_info[0] | select(.scope == "global") | .prefixlen'
man ip
:
,
-j
,-json
- dl>
以 JavaScript 对象表示法 (JSON) 输出结果。
对于 GNU awk
,您可以使用 gensub
:
txt='scope global'
ip -o -f inet addr show | \
awk -v search="$txt" '$0 ~ search{print gensub(/.*\//,"",1,$4)}'
这里,
-
-v search="$txt"
- 将txt
的值作为awk
变量传递给search
-
$0 ~ search
- 检查整行是否匹配 -
gensub(/.*\//,$4)
- 删除第四个字段中包括最后一个斜杠在内的所有内容(替换为空字符串 (""
),仅执行一次搜索 (1
))。
这应该只输出两位或一位数的子网掩码,如 24
:
ip -o -f inet addr show | grep -Po "/\K[[:digit:]]{1,2}(?=.*scope\sglobal)"
如果你想用斜杠 /24
输出:
ip -o -f inet addr show | grep -Po "/[[:digit:]]{1,2}(?=.*scope\sglobal)"
我在您的命令中使用了正则表达式来选择 /
之后的所有内容
ip -o -f inet addr show | awk '/scope global/ {print $4}' | grep -o '[^/]*$'