user10792602
user10792602

Reputation: 41

How to sort by numbers that are part of a filename in bash?

I'm trying to assign a variable in bash to the file in this directory with the largest number before the '.tar.gz' and I'm drawing a complete blank on the best way to approach this:

ls /dirname | sort   
daily-500-12345.tar.gz  
daily-500-12345678.tar.gz  
daily-500-987654321.tar.gz  
weekly-200-1111111.tar.gz  
monthly-100-8675309.tar.gz

Upvotes: 2

Views: 1196

Answers (1)

wjandrea
wjandrea

Reputation: 32944

sort -Vrt - -k3,3
  • -V Natural sort
  • -r Reverse, so you can use head -1 to get the first line only
  • -t - Use hyphen as field separator
  • -k3,3 Sort using only the third field

Output:

daily-500-987654321.tar.gz
daily-500-12345678.tar.gz
monthly-100-8675309.tar.gz
weekly-200-1111111.tar.gz
daily-500-12345.tar.gz

Upvotes: 6

Related Questions