Skip to content
Advertisement

Linux how to remove files in one folder where prefixes don’t match another folder?

I want to remove extra files in one folder where the prefix file names don’t match those in the other. A simple example will show:

JavaScript

From folderA I want to remove frame0002.jpg and frame0006.jpg because those frameXXXX prefixes don’t exist in folderB.

How can I do this automatically in 1 command line statement? Assume that the frameXXXX format will be the same for all files between both.

Cheers

Advertisement

Answer

You can use find together with the -exec option.

A basic format would be find . -exec sh -c 'echo {} | grep frame' ;.

Search with find in the folderA and execute a rm if your condition match (or not match). Useful commands are: sed, grep and && rm {}, || rm {}.

EDIT:

JavaScript

Remove the last echo to invoke the delete if you like the output.

EDIT: Fixed and/or, if grep does not match with the second find than remove the file.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement