Matengo
Matengo

Reputation: 19

unix find oldest file in directory by date in filename

I'm trying to find the oldest file in a directory by looking at the date in the file name.

Example of files:

AA_20150408010101.txt
AA_AA_20150408020202.txt
BB_20150408030303.txt

I tried a lot of commands, but this command below is what is closest to the desired result:

ls -lr | head -1

Upvotes: 1

Views: 2379

Answers (2)

Walter A
Walter A

Reputation: 19982

Strip the filenames to simple dates, search the first date and look with ls what the file was.

ls *$(ls | sed -e 's/.*_//' -e 's/.txt//' | sort -n | head -1).txt | head -1

Upvotes: 0

Sam Protsenko
Sam Protsenko

Reputation: 14743

Try this:

ls -1 | sed 's/^\([^0-9]*\)\([0-9]\+\.txt\)/\2\1/g' | sort -n | head -1 | sed 's/^\([0-9]\+\.txt\)\(.*\)/\2\1/g'

This command do next:

  1. Print files list in current directory
  2. Move prefixes in file names in the end of file names
  3. Sort files numerically (as file names are started from timestamps now)
  4. Leaves only file with oldest timestamp.
  5. Moves prefixes back.

Though timestamps in file names look a bit strange: you already have timestamp in file inode, which you can see using stat command, so why using additional timestamps in file names? I can see only one case for this: if file modifying time was changed artificially (e.g. with touch command).

Upvotes: 3

Related Questions