Sort strings with numbers naturally with GNU sort

Say you have a list of filenames or identifiers with numbers, e.g.

unknowns.txt:

unknown_E1_2
unknown_E1_1
unknown_E2_45
unknown_E10_34
unknown_E1_10
unknown_E1_23

and you want to sort them “naturally”, e.g. unknown_E1_2 should come before unknown_E1_10. If you would just sort them as strings (character by character), 10 would come before 2, because the character ‘1’ comes before ‘2’, and the trailing ‘0’ just doesn’t matter for the sort order anymore.

sort from the GNU coreutils let’s you do this easily with the -V switch. Note that this not only works for numbers at the end of a string, but also for the numbers in the middle:

# sort -V unknowns.txt
unknown_E1_1
unknown_E1_2
unknown_E1_10
unknown_E1_23
unknown_E2_45
unknown_E10_34

See Ned Batchfelder’s blog post on how to do this in Python. Especially check out Toothy’s comment for a brief solution.

Add directory hierarchy to PATH, or: addpath(genpath()) in bash

It’s actually pretty simple. Say you want to add all folders below you $HOME/bin to PATH, all you need is the following:

PATH=$(find $HOME/bin -type d | tr "\\n" ":")$PATH

The find $HOME/bin -type d returns a list of all folders below $HOME/bin. The tr "\\n" ":" replace the newlines in the find-result with colons.