Sort scientific-notation measurements with GNU sort -g
An export containing 1e3 and 20 needs a numeric comparison that understands exponents. GNU sort has separate modes for ordinary decimal numbers and general floating-point notation.
Run the example
Tested on Linux with GNU Bash 5.2.37, coreutils 9.7, grep 3.11 and diffutils 3.10. Use one Bash session and a text editor. Create a disposable working directory before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save as demo_linux_sort_scientific_notation.sh:
set -euo pipefail
export LC_ALL=C
printf 'Decimal mode:\n'
printf '%s\n' 1e3 20 3e1 -2e2 | sort -n
printf 'General mode:\n'
printf '%s\n' 1e3 20 3e1 -2e2 | sort -gRun it:
bash demo_linux_sort_scientific_notation.shObserved output:
Decimal mode:
-2e2
1e3
3e1
20
General mode:
-2e2
20
3e1
1e3-n compares the initial decimal portion and does not interpret the exponent. -g converts each numeric value using a floating-point representation, so the second result follows the values -200, 20, 30 and 1000. The C locale makes the decimal separator predictable.
Limits and input policy
Use this for measurements whose precision fits the conversion. General numeric sorting can lose information for very long numbers; ordinary decimal -n comparisons avoid that floating-point conversion. Neither option is a schema validator: reject malformed values before sorting a production export. Non-numeric text, infinities and NaNs have their own ordering rules.
Clean up
Remove the saved script and the empty working directory in the same Bash session:
rm -- demo_linux_sort_scientific_notation.sh
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before removing anything else.
Reference
Acknowledgements
This post was created with assistance from AI.