I want to sort a set of files with the same number of '-' delimiters in each filename (with -n for numeric sorting).
Here is an example list
/home/flora/edvart/docs/schimmel-01.png
/home/flora/edvart/docs/schimmel-02.png
/home/flora/edvart/docs/schimmel-03.png
/home/flora/edvart/docs/schimmel-04.png
/home/flora/edvart/docs/schimmel-05.png
/home/flora/edvart/docs/schimmel-06.png
/home/flora/edvart/docs/schimmel-07.png
/home/flora/edvart/docs/schimmel-08.png
/home/flora/edvart/docs/schimmel-09.png
/home/flora/edvart/docs/schimmel-10.png
/home/flora/edvart/docs/schimmel-11.png
/home/flora/edvart/docs/schimmel-12.png
/home/flora/edvart/docs/schimmel-13.png
Here is the code I am using
for fl in "$@"; do
fnme=${fl##*/}
ftyp=${fl##*.}
fdir=${fl%/*}
fnam=${fnme%.*}
nf=$( echo "$fnam" | awk -F '-' '{print NF}')
ifld=$(( nf + 1 ))
find "$fdir" -type f -name "${fnam}-*.png" |
awk -F'[-.]' '{print $(NF-1), $0}' RS='\0' ORS='\0' |
sort -znt '-' -k "$ifld"n |
while IFS= read -r flimg
do
echo "$flimg"
done
done
But when I try with the first three files being-1, -2, -3, the result is still not sorted numerically
/home/flora/edvart/docs/schimmel-04.png
/home/flora/edvart/docs/schimmel-05.png
/home/flora/edvart/docs/schimmel-06.png
/home/flora/edvart/docs/schimmel-07.png
/home/flora/edvart/docs/schimmel-08.png
/home/flora/edvart/docs/schimmel-09.png
/home/flora/edvart/docs/schimmel-10.png
/home/flora/edvart/docs/schimmel-11.png
/home/flora/edvart/docs/schimmel-12.png
/home/flora/edvart/docs/schimmel-13.png
/home/flora/edvart/docs/schimmel-1.png
/home/flora/edvart/docs/schimmel-2.png
/home/flora/edvart/docs/schimmel-3.png
find | sort -zwon't work. Either usefind -print0or remove the-z. And if you're staying with the-zyou need to read NULL-delimited lines in yourwhile readwithread -d ''. Although to be honest just replacing that loop entirely withtr '\0' '\nwould be betterfind "$fdir" -type f -name "${fnam}-*.png" -print0 | sort -znt '-' -k "$ifld"n |and usingwhile IFS= read -d '' flimg, but got the same output as before. I think thesort -ktries also to pick the.pngpart.-Vrather than-n. Also, as mentioned by @roaima, use-print0if you're going to usesort -z. Given that you're working with arbitrary filenames, I would not recommend relying on newlines as the delimiter - NUL-separated is the right way to do it.-print0now.