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
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
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).
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
)).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)"
I used regex on your command to select everything after /
ip -o -f inet addr show | awk '/scope global/ {print $4}' | grep -o '[^/]*$'