Reputation: 35
I am trying to find the date of the oldest log file that's at least 10 days old underneath the /home/
directory.
find /home -type f –name "*.log" –mtime +10 -ls | sort | head - n 1 >>/home/text.txt
Am using +10 since I need to find the date after 10 days period.
startDate = cut –d '_' –f20,22 text.txt to get the date.
But this code is not working correctly. Any suggestions please?
Upvotes: 0
Views: 755
Reputation: 63902
You can try the next:
oldest=$(stat -f "%m%t%Sm %N" /home/**/*.log | sort -n | head -1 | cut -f2)
or
oldest10=$(find /home/ -type f –name “*.log” –mtime +10 -print0 | xargs -0 stat -f "%m%t%Sm" | sort -n | head -1 | cut -f2)
Explanation:
find
finds the right filesstat
prints the date in format "seconds TAB date"sort
sorts by seconds (numerically) - lowest number (seconds) first (so it is the oldest)head
get the first line (oldest)cut
removes the seconds field.if you have GNU find, you can use the -printf
to get the "seconds TAB date" and not need to use the xargs
and stat
commands, e.g:
find arguments -printf "%T@\t%c\n" | sort -n | head -1 | cut -f2
Upvotes: 1
Reputation: 84551
It appears what you want to do is use find to locate the oldest log file over 10 days old below the /home/ directory. If that is your goal, then you can use a find
command similar to:
find /home -type f -name "*.log" -mtime +10 -printf "%TY%Tm%Td%TH%TM%TS %p\n" | \
sort | head -n 1 >> /home/text.txt
The output before the head
command will be a list of files found sorted in ascending order as follows (shown with "*.c" pattern):
20140621130603.9932529560 ./fill8bit.c
20140623130713.1503117800 ./strtol2.c
20140623133243.9487796380 ./strtol1.c
20140623215536.9085778830 ./mpg.c
...
The head -n1 simply takes the first. That being:
20140621130603.9932529560 ./fill8bit.c
Upvotes: 0