Sorting with gawk expression (supported by bash's loopreadarray):
Sample array of filenames containing whitespaces:
filearray=("dir1/name 0010.pdf" "dir2/name 0003.pdf" "dir3/name 0040.pdf") readarray -t sortedfilearr < <(printf '%s\n' "${filearray[@]}" | awk -F'/' ' BEGIN{PROCINFO["sorted_in"]="@ind_num_asc"PROCINFO["sorted_in"]="@val_num_asc"} { a[$NF]=$0a[$0]=$NF } END{ for(i in a) print a[i]i}') The output:
echo "${sortedfilearr[*]}" dir2/name 0003.pdf dir1/name 0010.pdf dir3/name 0040.pdf Accessing single item:
echo "${sortedfilearr[1]}" dir1/name 0010.pdf That assumes there's only one file with a given name in the array and that no file path containcontains newline characters. Note that the numerical sorting of the keysvalues in @ind_num_asc@val_num_asc only applies to the leading numerical part of the key (none in this example) with fallback to lexical comparison (based on strcmp(), not the locale's sorting order) for ties.