Friday, March 29, 2013

Finding Files in Linux Based on Known Time

I've slowly become a command line convert even to the point of finding it easier to just straight code in vi rather than download each to my box.  There's so much control over everything you do & you're uninhibited by what you can find within your program files.

However one thing I think that keeps people around in the wonderful world of GUIs is the ability to see files in a tree structure.  It's very visual, we all can process the information incredibly quickly.  And this is incredibly useful for utilizing what we do best which is make sense of unstructured data.  & yes I know it's a stretch to call a grouping of pictures with clearly defined labels "unstructured".  However, like creating the super long specialized view for looking at an entry in the database, sometimes it's just easier to take the simple search and then scan for what you need, especially if it's a one time use case.  This was before I discovered that burred within the man pages, "find" is incredibly powerful.

Using find to search a given time range

So I needed to find a file that was last modified between 5am and 5:10am on my system.  I had no idea what the file would be, but I figured that I should get the list of all the files and narrow from there.  The immediate issue you'll notice with find is that everything is based from now.  Which is great if you're searching generally or have the exact minute difference from where you were today and the time your file exists.  Having to constantly update that would defeat the intent of making life easy.

The solution comes with -newerXY an option that allows you to look for newer files matching the parameters that are put in X, Y and as the argument.  Since we have a time and not a particular file we're going to specify Y = t.  X can be used to specify time of creation, modification, or access.

For example to find all files in root that have been modified between 5:00am and 5:10am on 28 March:
find / -newermt '28 March 2013 5:00' -not -newermt '28 March 2013 5:10'

And this data become even more useful when able to sort and utilize the powers of ls.  The magic of xargs allows us in this case to pipe the results of this query as the "file system" to list and sort.

For example to nicely format the above files with timestamps and in descending order:
find / -newermt '28 March 2013 5:00' -not -newermt '28 March 2013 5:10' | xargs ls -t -l
 
Piping even further, you can refine the search for the file names or even more though grep.   But that's up to your own personal application.  You can keep piping forever Mario, but the princess is still in another castle!


Other bars to sample around this problem:
Virtuelvis
Stack Overflow -> this is the place to go for all your programming woes
Super User -> similar to Stack Overflow
Cyber Citi xargs

</sidebar>

No comments:

Post a Comment