I've been browsing around and trying to find the answer - bonus points for doing this in the shortest number of characters.

So I have file1.ex1 file2.ex1 file1.ex2 but no file2.ex2

I want to delete all the ex1 files, but only if ex2 version exists first.

So I assume this means I need to get a directory listing of all files ending in the extension I want to keep, piping that through and searching for which ones match the first part of the filename, then piping that into a delete command.

I want to use standard linux fu as I'm doing this on unraid.

I know this is easy for most of you, which is why I added to do it in least number of characters for a challenge! Oh, and this should work in all subdirectories matching to whatever is in that subdirectory only.



1 Answer 1

find . -name "*.ex1" -type f -exec sh -c '[ -f "${1%1}2" ] && echo rm "$1"' sh {} \;

This finds all regular files with suffix .ex1 recursively in the current directory and executes the shell script inside of the single quotes for each file ($1) found. It only prints the rm command it would execute.

  • [ -f "${1%1}2" ] && tests if argument $1 exists with 2 as last character. ${1%1} removes the last 1 and we replace it with 2. The [ -f ... ] && tests if the file exists and executes the following command if the condition is true.

You can remove the echo and run the command again to really delete the files.

If you want to delete the files only in the current directory and not its subdirectories:

for i in *.ex1; do [ -f "${i%1}2" ] && echo rm "$i"; done

Again, you have to remove the echo to execute rm.

  • 1
    Nice! Trying it out now. Thankyou!
    – Marshalleq
    Jun 30, 2019 at 2:07
  • 1
    So because files called ex1 and ex2 are examples only, if I wanted to delete all files that are .doc with *.odt but only where *.odt exists, the following would be correct? find . -name ".doc" -type f -exec sh -c '[ -f "${doc%1}odt" ] && echo rm "$1"' sh {} \;
    – Marshalleq
    Jun 30, 2019 at 2:12
  • 1
    If you want to delete .doc files where an .odt file exists, change *.ex1 to *.doc and ${1%1}2 to ${1%doc}odt (or ${i%1}2 to ${i%doc}odt). And don't forget to remove the echo if the output looks okay.
    – Freddy
    Jun 30, 2019 at 2:18
  • 1
    Tried the multi-folder version on a single folder and that works! Thankyou, will try it on a nested folder once I've copied across the duplicates (as odd as that sounds). Thanks, you're a genius!
    – Marshalleq
    Jun 30, 2019 at 2:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .