Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Created October 26, 2025 06:48
Show Gist options
  • Select an option

  • Save ormaaj/b25b871e12f42026e88fca7cc7aa2f33 to your computer and use it in GitHub Desktop.

Select an option

Save ormaaj/b25b871e12f42026e88fca7cc7aa2f33 to your computer and use it in GitHub Desktop.
Numeric sort files matching a pattern (bash or ksh93)
if [[ -v KSH_VERSION ]]; then
typeset -n BASH_REMATCH=.sh.match
else
shopt -s extglob lastpipe
enable -f asort{,}
fi
touch file_{7..13}.pdf
unset -v a b
typeset -A a
for x in file_+([[:digit:]]).pdf; do
[[
-f $x &&
$x =~ ^[^[:digit:]]*([[:digit:]]+).*
]] && a+=([${BASH_REMATCH[1]}]=$x)
done
typeset -a b=("${!a[@]}")
${BASH_VERSION+\:} set -sK :n -A b
${KSH_VERSION+\:} asort -n b
for x in "${!b[@]}"; do
printf "%s${b[x+1]+ }" "${a[${b[x]}]}"
done
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment