nirtidognu
nirtidognu

Reputation: 53

How to read latest file created |pick the one is latest

I have a folder in which files are created whenever I run my script. First time I run it creates demo_1.txt. Next time I run it creates demo_2.txt. And so on.

I want to read the latest created file based on timestamp.

If you see below the latest created file is demo_4.txt according to timestamp. That's the file I want to read.

demo_1.txt  => timestamp 8:00
demo_2.txt  => timestamp 8:02
demo_3.txt  => timestamp 8:03
demo_4.txt  => timestamp 8:04

This only half works. It reads all the files and appends them to file.txt.

find . -iname 'List*' -cm -60 -exec cat '{}' >> file.txt

How do I fix it to fetch just the latest file?

Upvotes: 2

Views: 220

Answers (1)

grant
grant

Reputation: 9

stat * -c "%y-%n" | sort -r

Will list all the files in your current directory, sorted in descending order by time of last data modification.

If you just require the last modified file, the appropriate command would be

stat * -c "%y-%n" | sort -r | head -n 1

or

stat * -c "%y-%n" | tail -n 1

Upvotes: 1

Related Questions