Wednesday, April 13, 2022

[SOLVED] delete file - specific date

Issue

How to Delete file created in a specific date??

ls -ltr | grep "Nov 22" | rm -- why this is not wrking??


Solution

There are three problems with your code:

  • rm takes its arguments on its command line, but you're not passing any file name on the command line. You are passing data on the standard input, but rm doesn't read that¹. There are ways around this.
  • The output of ls -ltr | grep "Nov 22" doesn't just consist of file names, it consists of mangled file names plus a bunch of other information such as the time.
  • The grep filter won't just catch files modified on November 22; it will also catch files whose name contains Nov 22, amongst others. It also won't catch the files you want in a locale that displays dates differently.

The find command lets you search files according to criteria such as their name matching a certain pattern or their date being in a certain range. For example, the following command will list the files in the current directory and its subdirectories that were modified today (going by GMT calendar date). Replace echo by rm -- once you've checked you have the right files.

find . -type f -mtime -2 -exec echo {} +

With GNU find, such as found on Linux and Cygwin, there are a few options that might do a better job:

  • -maxdepth 1 (must be specified before other criteria) limits the search to the specified directory (i.e. it doesn't recurse).
  • -mmin -43 matches files modified at most 42 minutes ago.
  • -newermt "Nov 22" matches files modified on or after November 22 (local time).

Thus:

find . -maxdepth 1 -type f -newermt "Nov 22" \! -newermt "Nov 23" -exec echo {} +

or, further abbreviated:

find -maxdepth 1 -type f -newermt "Nov 22" \! -newermt "Nov 23" -delete

With zsh, the m glob qualifier limits a pattern to files modified within a certain relative date range. For example, *(m1) expands to the files modified within the last 24 hours; *(m-3) expands to the files modified within the last 48 hours (first the number of days is rounded up to an integer, then - denotes a strict inequality); *(mm-6) expands to the files modified within the last 5 minutes, and so on.

¹ rm -i (and plain rm for read-only files) uses it to read a confirmation y before deletion.



Answered By - Gilles 'SO- stop being evil'
Answer Checked By - David Goodson (WPSolving Volunteer)