如何按字典序对提取出的IP地址进行排序以匹配预期输出
The issue here is that the default sort command uses lexicographical (string) sorting, which compares characters one by one rather than treating each IP segment as a numeric value. That's why you see results like 127.0.0.1 appearing before 7.7.7.8—the string "1" has a lower ASCII value than "7", even though 7 is numerically smaller than 127.
Simple Solution: Use GNU Sort's Version Sort (sort -V)
If you're on a system with GNU sort (most Linux distributions), the easiest fix is to use the -V (version sort) flag. This option is designed specifically for sorting strings with numerical segments (like IP addresses, version numbers) by treating each segment as a number:
find /root/data -type f -exec grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" {} \; | sort -V | uniq -c | awk '{print $2}'
sort -V will automatically parse each IP segment as a numeric value, sorting them in the order you expect: starting with 0.0.0.0, then 7.7.7.8, followed by the 15.x, 26.x, etc., ranges, and finally the 127.x and higher segments.
Alternative for Non-GNU Systems (e.g., BSD/macOS)
If sort -V isn't available, you can use awk to normalize each IP segment to a fixed 3-digit width (padding with leading zeros), which makes lexicographical sorting match numerical sorting. Here's how:
find /root/data -type f -exec grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" {} \; | uniq | awk -F. '{printf("%03d.%03d.%03d.%03d\t%s\n", $1,$2,$3,$4,$0)}' | sort | cut -f2
How this works:
uniqfirst removes duplicates (we moved this earlier to avoid processing redundant entries)awkformats each IP with leading zeros (e.g.,7.7.7.8becomes007.007.007.008), paired with the original IPsortnow works correctly on the padded stringcutextracts the original (unpadded) IP from the sorted output
This will produce the exact ordered list you're expecting.
内容的提问来源于stack exchange,提问作者Patrick

