Reputation: 380
I have tried this suggestion :
ip -o -f inet addr show | awk '/scope global/ {print $4}'
but that outputs IP address with the subnet mask number:
192.168.1.108/24
I only want the number 24
Upvotes: 0
Views: 2189
Reputation: 19555
ip addr show
can output JSON data, so it makes it reliably explicit to parse with jq
:
ip \
-family inet \
-json \
addr show |
jq -r '.[].addr_info[0] | select(.scope == "global") | .prefixlen'
man ip
:
-j
,-json
Output results in JavaScript Object Notation (JSON).
Upvotes: 6
Reputation: 626804
With GNU awk
, you may use gensub
:
txt='scope global'
ip -o -f inet addr show | \
awk -v search="$txt" '$0 ~ search{print gensub(/.*\//, "", 1, $4)}'
Here,
-v search="$txt"
- passes the value of txt
to awk
as search
variable$0 ~ search
- checks if there is a match in the whole linegensub(/.*\//, "", 1, $4)
- removes all up to an including the last slash in the fourth field (replaces with an empty string (""
), search is performed once only (1
)).Upvotes: 2
Reputation: 27
I used regex on your command to select everything after /
ip -o -f inet addr show | awk '/scope global/ {print $4}' | grep -o '[^/]*$'
Upvotes: 0
Reputation: 380
this should only output the two or single digit subnet mask number like 24
:
ip -o -f inet addr show | grep -Po "/\K[[:digit:]]{1,2}(?=.*scope\sglobal)"
if you want it to output with the slash /24
:
ip -o -f inet addr show | grep -Po "/[[:digit:]]{1,2}(?=.*scope\sglobal)"
Upvotes: 1