How to Sort IP Addresses with a Simple Shell Script
This guide walks through a real‑world operations scenario, showing how to write and run a Bash script that uses the sort command with numeric and field options to correctly order a list of IP addresses for easier log analysis and network troubleshooting.
In daily operations we often need to manage and sort IP addresses for log analysis, traffic monitoring, and troubleshooting.
Given a sample list of ten unsorted IPs, we create a Bash script sort_ips.sh that reads the list from /mnt/data/ip.txt and writes the numerically sorted result to /mnt/data/sorted_ip.txt using the command:
#!/bin/bash
# Define input and output files
input_file="/mnt/data/ip.txt"
output_file="/mnt/data/sorted_ip.txt"
# Sort IP addresses numerically by each octet
sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 $input_file > $output_file
# Display the sorted IPs
cat $output_fileThe -n option forces numeric sorting, -t . sets the dot as the field delimiter, and the series of -k options sort each octet in order.
After granting execution permission ( chmod +x sort_ips.sh) and running the script ( ./sort_ips.sh), the sorted_ip.txt file contains the IPs in proper order:
3.252.10.92
10.184.34.10
33.46.4.10
35.185.72.151
83.91.145.234
83.119.149.68
103.187.9.50
184.142.237.167
193.232.67.195
217.40.57.147-n sorts numerically; -t . sets the delimiter; -k 1,1 -k 2,2 -k 3,3 -k 4,4 sorts each octet individually; $input_file is the source file; $output_file receives the sorted output; cat $output_file displays the result.
This example shows how a short shell script can reliably sort IP addresses, a technique that can be extended to other text‑data sorting tasks in system administration.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
