Liably
Liably

Reputation: 337

How to select most recent file based off of date in filename

I have a list of files

- backups/
  - backup.2017-08-28.zip
  - backup.2017-08-29.zip
  - backup.2017-09-2.zip

I would like to be able to upload the most recent back to a server which I can do with command:

dobackup ~/backups/backup.2017-09-2.zip

My questions is: Within a .sh file (so I can start an automated/cron job for this) how can I get the latest file name to then run that command?

Limitation: I must use the date on the filename not the modifcation metadata.

Upvotes: 2

Views: 2000

Answers (2)

markp-fuso
markp-fuso

Reputation: 34484

Adding a couple more files:

backup.2017-08-28.zip
backup.2017-08-29.zip
backup.2017-09-10.zip
backup.2017-09-2.zip
backup.2017-09-28.zip
backup.2017-09-3.zip

How about something like this, though granted, a bit convoluted:

ls -1 backup*zip | sed 's/-\([1-9]\)\./-0\1\./g' | sort [-r] | sed 's/-0\([1-9]\)\./-\1\./g'
  • sed is looking for a match like -[0-9].
  • the escaped/matching parens - \( and \) designates a pattern we want to reference in the replacement portion
  • the new pattern will be -0\1. where the \1 is a reference to the first pattern wrapped in escaped/matching parens (ie, \1 will be replaced with the single digit that matched [0-9])
  • our period (.) is escaped to make sure it's handled as a literal period and not considered as a single-position wildcard
  • at this point the ls/sed construct has produced a list of files with 2-digit days
  • we run through sort (or sort -r) as needed
  • then run the results back through sed to convert back to a single digit day for days starting with a 0
  • at this point you can use a head or tail to strip off the first/last line based on which sort/sort -r you used

Running against the sample files:

$ ls -1 backup*zip | sed 's/-\([1-9]\)\./-0\1\./g' | sort | sed 's/-0\([1-9]\)\./-\1\./g'

backup.2017-08-28.zip
backup.2017-08-29.zip
backup.2017-09-2.zip
backup.2017-09-3.zip
backup.2017-09-10.zip
backup.2017-09-28.zip

# reverse the ordering
$ ls -1 backup*zip | sed 's/-\([1-9]\)\./-0\1\./g' | sort -r | sed 's/-0\([1-9]\)\./-\1\./g'

backup.2017-09-28.zip
backup.2017-09-10.zip
backup.2017-09-3.zip
backup.2017-09-2.zip
backup.2017-08-29.zip
backup.2017-08-28.zip

Upvotes: 2

anubhava
anubhava

Reputation: 785196

You can sort it on 2nd field delimited by dot:

printf '%s\n' backup.* | sort -t '.' -k2,2r | head -1

backup.2017-09-2.zip

Upvotes: 2

Related Questions