Bash Sort by Numeric Substring: How to Sort Files in Numerical Order using Bash

Abstract: Sorts files with numeric substrings in true numerical order by extracting digits and using sort -n to prevent lexicographical errors.

Created: 2026-08-26 by
To sort files by a numeric substring in Bash, you must extract the number using parameter expansion or sed, then use the sort command with the -n flag for numerical ordering. This approach avoids fragile regex patterns and ensures that file10 appears after file2, not before it. The most robust method combines ls output parsing with a custom sort key to handle variable-length numbers correctly.

Understanding Numeric Sorting Behavior

By default, the sort command performs lexicographical (alphabetical) sorting. In this mode, "file10" comes before "file2" because the character '1' is less than '2'. To achieve true numerical order, you need to instruct sort to interpret the leading digits as integers. However, standard sort -n only works if the entire string is a number or if the number is at the very beginning of the line. When dealing with filenames like image_05.jpg, image_20.jpg, and image_3.jpg, simple numeric sorting fails because the prefix "image_" interferes with the digit recognition.

You can see this behavior clearly by creating a test directory. Run the following commands to generate sample files:

mkdir -p test_sort
touch test_sort/file1.txt
touch test_sort/file10.txt
touch test_sort/file2.txt
touch test_sort/file20.txt

If you run ls test_sort/ | sort, the output will be: file1.txt, file10.txt, file2.txt, file20.txt. This is incorrect for human expectations. You need a way to isolate the numeric portion of each filename so sort can compare them accurately.

Method 1: Using Sort Key Fields

The most efficient solution uses the -k option in the sort command. This option allows you to specify which field in each line should be used for comparison. If your filenames follow a consistent pattern, such as prefix_number.extension, you can tell sort to look at the second field.

First, list the files using ls with the -1 flag to ensure one file per line. Then pipe the output to sort.

ls -1 test_sort/ | sort -t_ -k2,2n

Here, -t_ sets the delimiter to an underscore. -k2,2 specifies that only the second field (the number between underscores) should be considered. The n flag enables numeric sorting for that specific field. This command correctly outputs: file1.txt, file2.txt, file10.txt, file20.txt. Note that if your filenames do not contain a consistent delimiter, this method requires adjustment. For example, if the name is img01.png, you might need to use -k1.4,1.5n to sort characters 4 through 5 numerically.

Method 2: Extracting Numbers with Parameter Expansion

For more complex filenames where delimiters are inconsistent, you can use Bash parameter expansion to strip non-numeric characters. This method is pure Bash and does not rely on external tools like awk or sed for the extraction logic, making it faster for large directories.

Create a script that iterates over the files, extracts the number, and prints it alongside the filename. Then pipe this output to sort -n.

for f in test_sort/*; do
  num=$(basename "$f" | sed 's/[^0-9]//g')
  echo "${num} ${f}"
done | sort -n | cut -d' ' -f2-

In this snippet, sed 's/[^0-9]//g' removes all non-digit characters from the basename. The resulting output is prepended with the extracted number. The sort -n command sorts these lines numerically based on the first field. Finally, cut -d' ' -f2- removes the temporary numeric prefix, leaving only the original filenames in sorted order.

This approach is particularly useful when you have files like report_v2_final.pdf and report_v10_draft.pdf. The sed command extracts "2" and "10", allowing correct sorting. However, be cautious with filenames containing multiple distinct numbers, as this method concatenates all digits. If you have file1_part2.txt, the extracted number becomes "12", which may lead to incorrect sorting relative to file1_part10.txt (extracted as "110"). In such cases, Method 1 with precise field selection is superior.

Handling Edge Cases and Permissions

When working with large datasets, performance matters. Piping many files through multiple processes can be slow. If you are processing thousands of files, consider using find with -printf to generate the sort keys directly, reducing overhead. Additionally, always check file permissions before attempting to read or move sorted files. If you encounter permission errors, refer to guides on improving bash performance and securing passwords to understand best practices for user privileges.

Another common issue arises with hidden files (those starting with a dot). Standard ls commands often exclude these unless the -a flag is used. Ensure you include -a if your directory contains configuration files or backup versions that start with a dot. Also, remember that sort treats uppercase letters differently than lowercase ones depending on locale settings. To ensure consistent alphabetical fallback, set the LC_ALL=C environment variable before running your sort command.

Frequently Asked Questions

Why does my sort command fail with "invalid key specification"?

This error usually occurs when the field separator specified with -t does not exist in the data, or the field number exceeds the available fields. Check your delimiter carefully; if your filename uses spaces instead of underscores, change -t_ to -t' '. Also, verify that the field index starts at 1, not 0.

Can I sort files by the last number in the filename?

Yes, but it requires more complex field definitions. If your format is name_num_suffix, you can target the second field. If the number is at the end, such as data_100.csv, you can use -k2,2n assuming the underscore is the delimiter. For variable suffixes, extracting the number via sed or awk into a prepend field is safer.

How do I reverse the sort order to descending?

Add the -r flag to your sort command. For example, sort -n -r will sort numbers from highest to lowest. You can combine this with key specifications like sort -k2,2nr to reverse the numeric sort for a specific field.

What if my filenames contain spaces?

Spaces in filenames break simple echo based parsing if not quoted properly. Use find . -maxdepth 1 -type f -print0 | xargs -0 ... to handle null-separated strings safely. Alternatively, stick to the parameter expansion loop shown above, ensuring variables are always double-quoted to preserve whitespace.

Is there a way to sort by date modified instead of filename?

Yes, use ls -lt which lists files sorted by modification time, newest first. To sort oldest first, add -r. This is independent of the filename content and relies on filesystem metadata. If you need to sort by creation time on macOS, use ls -lV or stat commands to extract birth dates.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More