Search code examples
bashcentos

delete the older file with the same name but different extension


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?


Solution

  • 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