如何在Bash中从ifconfig提取iface、inet及子网掩码并过滤输出?
Hey there! Let's break down how to pull out the network interface, IPv4 address, and subnet mask from ifconfig output in Bash—both for general cases and your specific example.
1. General Method for Any ifconfig Output
The most flexible way to parse ifconfig is using awk, since it handles the structured (but sometimes line-wrapped) output really well. Here's a reliable command:
ifconfig | awk ' # Capture the interface name when we hit the start of a new interface block /^[a-zA-Z0-9]+ / { iface = $1 } # When we find the "inet addr:" line, extract the IP and mask /inet addr:/ { split($2, addr_parts, ":") inet = addr_parts[2] split($4, mask_parts, ":") mask = mask_parts[2] printf "Interface: %s | IPv4: %s | Subnet Mask: %s\n", iface, inet, mask } '
How this works:
- The first pattern matches lines starting with an interface name (like
enp37s0oreth0) and stores the name in theifacevariable. - The second pattern targets lines with
inet addr:, splits the address and mask fields using:as a delimiter, then prints all three values in a readable format.
If you prefer a more compact approach using grep and paste, this also works:
ifconfig | grep -E "^[a-zA-Z0-9]+|inet addr:" | paste - - | awk '{ split($2, a, ":") split($4, m, ":") print $1, a[2], m[2] }'
2. Parsing Your Specific ifconfig Output
First, let's restate your provided output for clarity:
enp37s0 Link encap:Ethernet HWaddr 2c:41:38:15:41:30 inet addr:192.168.0.105 Bcast:192.168.0.255 Mask:255.255.255.0 inet6 addr: fe80::89be:e3f9:b746:19ed/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:4593332 errors:0 dropped:0 overruns:0 frame:0 TX packets:2313662 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:6506620971 (6.5 GB) TX bytes:182579364 (182.5 ...
Notice the interface name and IP/mask are all on one line here (likely a formatting quirk), so we can adjust the awk command to scan all fields instead of relying on line breaks:
echo "enp37s0 Link encap:Ethernet HWaddr 2c:41:38:15:41:30 inet addr:192.168.0.105 Bcast:192.168.0.255 Mask:255.255.255.0 inet6 addr: fe80::89be:e3f9:b746:19ed/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:4593332 errors:0 dropped:0 overruns:0 frame:0 TX packets:2313662 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:6506620971 (6.5 GB) TX bytes:182579364 (182.5 ..." | awk '{ iface = $1 for (i = 1; i <= NF; i++) { if ($i ~ /inet addr:/) { split($i, addr_parts, ":") inet = addr_parts[2] } if ($i ~ /Mask:/) { split($i, mask_parts, ":") mask = mask_parts[2] } } printf "Interface: %s\nIPv4 Address: %s\nSubnet Mask: %s\n", iface, inet, mask }'
Output you'll get:
Interface: enp37s0 IPv4 Address: 192.168.0.105 Subnet Mask: 255.255.255.0
内容的提问来源于stack exchange,提问作者Daniyal Ahmed

