Shell – Sort files by highest number in filename

filesshell-script

I've got a bunch of files all named like this:

name_file-1.txt
name_file-2.txt
name_file-3.txt
some_other_file-1.txt
some_other_file-2.txt

There are thousands of different filenames, some with just one -1.txt at the end, some with -1.txt, -2.txt-60.txt

I need to copy the highest numbers of each file, so name_file-3.txt, some_other_file-2.txt. How do I do that on a Linux command line?

Best Answer

With zsh:

typeset -A greatest
for f (*-*(n)) greatest[${f%-*}]=$f
cp -- $greatest /destination
  • *-*(n): non-hidden files whose name contains a - (*-*), sorted numerically ((n) glob qualifier).
  • ${f%-*}: part of the filename up to the right-most - (or to the end if there's no -).
  • $greatest: expands to the non-empty values of the associative arrays. So here, for files that share the same root, only the file with the greatest number will be expanded.
Related Question