0

I have a lot of files like this in Linux:

File1.ext
File1.EXT
File2.ext
File2.EXT
.
.
.

I need to delete the older file between File1.ext and File1.EXT, File2.ext and File2.EXT, etc. Can I do this on Linux?

Cyrus
  • 84,225
  • 14
  • 89
  • 153

1 Answers1

0

We can use the stat command to get the epoch timestamp of the last modification on the file and use that to delete the older file.

We can then compare these timestamps in the shell with -gt for greater than and -lt for less than to delete the appropriate file.

#!/bin/sh -e

for f in *.ext; do
    # f = File1.ext
    base="$(basename "$f" .ext)" # File1
    last_modified="$(stat -c '%Y' "$f")"
    last_modified_next="$(stat -c '%Y' "${base}.EXT")"

    if [ "$last_modified" -gt "$last_modified_next" ]; then
        rm -f "$base.EXT"
    elif [ "$last_modified" -lt "$last_modified_next" ]; then
        rm -f "$f"
    fi
done
git-bruh
  • 333
  • 1
  • 7
  • Hi there, in the folder I have some files that have the same name but different extensions but also have files that only have one extension, so I get an error with the script because it didn't find a file to compare the date, how can I avoid this? thank you in advance – Johsttin Curahua Sep 22 '21 at 14:37
  • You could add such a logic below `base=...` and before `last_modified=...`. `[ -f "${base}.EXT" ] || continue` to ignore the current file if a corresponding file with extension EXT doesn't exist. – git-bruh Sep 22 '21 at 14:39