How to list the last modified files in a specific directory recursively
It may be a generic Linux question but I'll give it a try here.
I need a list of recently modified files very often and currently for it I am piping ls output to grep with the param on today or a certain hour, but I need to change the grep param frequently to get an updated list, being a bit unproductive.
Is there an easy command to list the last modified files on a certain path ?
24 Answers
To find the last 5 modified files from a certain directory recursively, from that directory run:
find . -type f -printf '%T@ %p\n' | sort -k1,1nr | head -5%T@with-printfpredicate offindwill get modification time since epoch for the files,%pwill print the file namessort -k1,1nrwill reverse numericallysortthe result according to the epoch timehead -5will get us the last modified five file names
If you just want to search only in the current directory (not recursively), use stat:
stat -c '%Y %n' * | sort -k1,1nr | head -5Or find:
find . -maxdepth 1 -type f -printf '%T@ %p\n' | sort -k1,1nr | head -5Check man find and man stat to get more idea.
It is so simple actually.To get the Most recent file in the currant directory:
ls -Art | tail -n 2
To get the Most recent file in another directory , for example in /opt/spark/ :
ls /opt/spark/ -Art | tail -n 1
This is when i use it on my cluster:
aa23916@picard03:/opt/spark/applicationHistory$ ls -Art | tail -n 2
app-20180124162809-0004
app-20180124163207-0005.inprogressSimple and easy : )
2The script below lists all files recursively inside a directory, edited shorter ago than an arbitrary time. Additionally, it displays the time span since the last edit.
It can be used with the command:
findrecent <directory> <time(in hours)>as shown below:
In this example, all files on my Desktop, edited less than 36 hours ago are listed.
The script
#!/usr/bin/env python3
import os
import time
import sys
directory = sys.argv[1]
try: t = int(sys.argv[2])
except IndexError: t = 1
currtime = time.time(); t = t*3600
def calc_time(minutes): # create neatly displayed time if minutes < 60: return "[edited "+str(minutes)+" minutes ago]" else: hrs = int(minutes/60); minutes = int(minutes - hrs*60) return "[edited "+str(hrs)+" hours and "+str(minutes)+" minutes ago]"
for root, dirs, files in os.walk(directory): for file in files: file = os.path.join(root, file); ftime = os.path.getctime(file) edited = currtime - ftime if edited < t: print(file, calc_time(int(edited/60)))How to use
- Create, if it doesn't exist yet, the directory
~/bin - Copy the script above into an empty file, save it as
findrecentin~/bin - Make the script executable
- Log out and back in and you're done
Note
- if no time is given, the script lists all files, edited in the last hour
- if a directory includes spaces, use quotes, like in the example
To get last 5 modified files execute the below command in the directory you looking for.
ls -lrt | tail -5