Search code examples
bashgnu-findutils

Write the file name before deleting


I want to delete all the .png files in a directory and save the delete files names in a text file. I managed to do this with the following command:

find . -name "*.png" -delete -print >> log.txt

Everything works fine and in the log I get the entire the path of the file deleted. But if there are multiple files to be deleted, the names placed in the log are all on the same line.

C:/Users/Dragos.Cazangiu/Desktop/TesteCyg/CMDER/New Bitmap Image3.pngC:/Users/Dragos.Cazangiu/Desktop/TesteCyg/CMDER/2.pngC:/Users/Dragos.Cazangiu/Desktop/TesteCyg/CMDER/New Bitmap Image.png

How can I make it put each file on a new line and also how can I add a message before the path, something like "The deleted file is: "

Thank you!


Solution

  • You can replace the -print predicate with this predicate:

    -exec printf 'The deleted file is: %s\n' {} \;
    

    so that the command looks like:

    find . -name "*.png" -delete -exec printf 'The deleted file is: %s\n' {} \; >> log.txt
    

    If you have GNU find, then you can use the -printf predicate as so:

    find . -name "*.png" -delete -printf 'The deleted file is: %p\n' >> log.txt