linuxbashshell

How to delete all files except the last day files in Linux?


Suppose these are my files:

file1 ==> 2024/07/10
file2 ==> 2024/07/9
file3 ==> 2024/07/9
file4 ==> 2024/07/8

I'm going to delete all files, except files which create date is yesterday (2024/07/09 is yesterday).

I know this find command, but I only know how to delete files older than N days, which keeps today files and yesterday files:

find . -mtime +2 -delete

Update2

I think it might be a way:

yesterday="$(date -d 'yesterday' '+%Y-%m-%d')"
while read -r file
do
    if [ "$yesterday" != "stat $file -c %y | awk -F ' ' '{print $1}'" ]
    then
        rm -vf "$file"
    fi
done < <(find . -type f)

I mean: if stat {} -c %y != $yesterday, then delete the file. But that deletes all files:(


Solution

  • Standard find uses 86400 second intervals from when the program started, to compute n in -mtime n / -mtime +n / -mtime -n.

    It appears the question is looking for intervals based on the calendar date.

    It is not obvious to me how to do this portably in a simple way. However, if GNU find is available, it has a -daystart option that allows for precisely this:

    Files to keep:

    find . -daystart -type f -mtime 1 -print
    

    Files to delete:

    find . -daystart -type f ! -mtime 1 -print
    

    Note that -mtime checks last modification timestamp, not file creation. These are likely to be different. There isn't a standard find option to check file creation timestamp (and filesystems may not store it). However, GNU find has an option that may help -newerBt:

    -newerXY reference
          Succeeds if timestamp X of the file being  considered  is  newer
          than timestamp Y of the file reference.  The letters X and Y can
          be any of the following letters:
    
          a   The access time of the file reference
          B   The birth time of the file reference
          c   The inode status change time of reference
          m   The modification time of the file reference
          t   reference is interpreted directly as a time
    
          Some combinations are invalid; for example, it is invalid for  X
          to  be t.  Some combinations are not implemented on all systems;
          for example B is not supported on all systems.  If an invalid or
          unsupported  combination  of  XY is specified, a fatal error re‐
          sults.  Time specifications are interpreted as for the  argument
          to  the -d option of GNU date.  If you try to use the birth time
          of a reference file, and the birth time cannot be determined,  a
          fatal error message results.  If you specify a test which refers
          to the birth time of files being examined, this test  will  fail
          for any files where the birth time is unknown.