Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ls to find files for a specific set of dates in Unix [closed]

Tags:

bash

command

unix

I have a set of files in a directory. I need to find files for a set of specific dates (For example if i need files from 16th Jan to 20th Jan). I tried using ls -ltr | grep <date> but it is taking too many steps to accomplish selecting the files. Is there any easier way to get this done. Thanks!

like image 818
Shash Avatar asked Feb 05 '13 08:02

Shash


People also ask

How do I search for files from a specific date?

Enter any date after datemodified: using the mm/dd/yyyy format to search for any files modified on the desired date. To find files modified between two dates, you can type the following. In this example, any files modified between January 1, 2022, and February 1, 2022, are displayed in the search results.

How do I find files older than a certain date in Unix?

You could start by saying find /var/dtpdev/tmp/ -type f -mtime +15 . This will find all files older than 15 days and print their names. Optionally, you can specify -print at the end of the command, but that is the default action.

How do you use ls with dates?

In order to ls by date or list Unix files in last modifed date order use the -t flag which is for 'time last modified'. or to ls by date in reverse date order use the -t flag as before but this time with the -r flag which is for 'reverse'.


2 Answers

I'm not sure how many files you have in your directory but something like this should be blindingly fast:

ls -al | awk '$6 == "Jan" && $7 >= 16 && $7 <= 20 {print $9}'

On my system, I see the following with dates slightly modified:

pax> ls -al | awk '$6 == "Jan" && $7 >= 16 && $7 <= 29 {print $9}'
kids_shares.ods
our_savings.gnumeric
photos

pax> ls -ald kids_shares.ods our_savings.gnumeric photos
-rw-r--r--   1 pax pax 51005 Jan 29 19:39 kids_shares.ods
-rw-r--r--   1 pax pax  2275 Jan 28 14:48 our_savings.gnumeric
drwxrwxrwx 130 pax pax  4096 Jan 29 21:47 photos

You can see that the dates match for the given files.

One thing to watch out for: if the file is recent, it will have a time in column 8. Beyond some age, ls starts putting the year in there. I have the vague recollection that it's somewhere around the six-month-old border but I'm not absolutely certain. You'll need to cater for that as well.

like image 105
paxdiablo Avatar answered Sep 19 '22 21:09

paxdiablo


Use find(1) instead, that will be much easier.

find . -mtime -$start -mtime +$end
like image 24
wich Avatar answered Sep 19 '22 21:09

wich