jasonmclose
jasonmclose

Reputation: 1695

How do I filter down a subset of files based upon time?

Let's assume I have done lots of work whittling down a list of files in a directory down to the 10 files that I am interested in. There were hundreds of files, and I have finally found the ones I need.

I can either pipe out the results of this (piping from ls), or I can say I have an array of those values (doing this inside a script). Doesn't matter either way.

Now, of that list, I want to find only the files that were created yesterday.

We can use tools like find -mtime 1 which are fine. But how would we do that with a subset of files in a directory? Can we pass a subset to find via xargs?

I can do this pretty easily with a for loop. But I was curious if you smart people knew of a one-liner.

Upvotes: 1

Views: 41

Answers (2)

John Kugelman
John Kugelman

Reputation: 361967

If they're in an array:

files=(...)
find "${files[@]}" -mtime 1

If they're being piped in:

... | xargs -d'\n' -I{} find {} -mtime 1

Note that the second one will run a separate find command for each file which is a bit inefficient.

If any of the items are directories and you don't want to search inside of them, add -maxdepth 0 to disable find's recursion.

Upvotes: 3

Paul Hodges
Paul Hodges

Reputation: 15418

Another option that won't recurse, though I'd just use John's find solution if I were you.

$: stat -c "%n %w" "${files[@]}" | sed -n "
     / $(date +'%Y-%m-%d' --date=yesterday) /{ s/ .*//; p; }"

The stat will print the name and creation date of files in the array.
The sed "greps" for the date you want and strips the date info before printing the filename.

Upvotes: 1

Related Questions