Operations 4 min read

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.

Liangxu Linux
Liangxu Linux
Liangxu Linux
How to Sort IP Addresses with a Simple Shell Script

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_file

The -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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AutomationLinuxSortingIP address
Liangxu Linux
Written by

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.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.