5. Shell Script

The natsort shell script is automatically installed when you install natsort with pip.

Below is the usage and some usage examples for the natsort shell script.

5.1. Usage

5.2. Description

natsort was originally written to aid in computational chemistry research so that it would be easy to analyze large sets of output files named after the parameter used:

$ ls *.out
mode1000.35.out mode1243.34.out mode744.43.out mode943.54.out

(Obviously, in reality there would be more files, but you get the idea.) Notice that the shell sorts in lexicographical order. This is the behavior of programs like find as well as ls. The problem is passing these files to an analysis program causes them not to appear in numerical order, which can lead to bad analysis. To remedy this, use natsort:

$ natsort *.out
mode744.43.out
mode943.54.out
mode1000.35.out
mode1243.34.out
$ natsort -t r *.out | xargs your_program

-t r is short for --number-type real. You can also place natsort in the middle of a pipe:

$ find . -name "*.out" | natsort -t r | xargs your_program

To sort version numbers, use the default --number-type:

$ ls *
prog-1.10.zip prog-1.9.zip prog-2.0.zip
$ natsort *
prog-1.9.zip
prog-1.10.zip
prog-2.0.zip

In general, all natsort shell script options mirror the natsorted() API, with notable exception of the --filter, --reverse-filter, and --exclude options. These three options are used as follows:

$ ls *.out
mode1000.35.out mode1243.34.out mode744.43.out mode943.54.out
$ natsort -t r *.out -f 900 1100 # Select only numbers between 900-1100
mode943.54.out
mode1000.35.out
$ natsort -t r *.out -F 900 1100 # Select only numbers NOT between 900-1100
mode744.43.out
mode1243.34.out
$ natsort -t r *.out -e 1000.35 # Exclude 1000.35 from search
mode744.43.out
mode943.54.out
mode1243.34.out

If you are sorting paths with OS-generated filenames, you may require the --paths/-p option:

$ find . ! -path . -type f
./folder/file (1).txt
./folder/file.txt
./folder (1)/file.txt
./folder (10)/file.txt
./folder (2)/file.txt
$ find . ! -path . -type f | natsort
./folder (1)/file.txt
./folder (2)/file.txt
./folder (10)/file.txt
./folder/file (1).txt
./folder/file.txt
$ find . ! -path . -type f | natsort -p
./folder/file.txt
./folder/file (1).txt
./folder (1)/file.txt
./folder (2)/file.txt
./folder (10)/file.txt