Write the file name before deleting

580 views Asked by At

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!

4

There are 4 answers

6
gniourf_gniourf On BEST ANSWER

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
3
James Brown On

A much more intuitive (TGIF :) way by using bash, rm, yes and awk. First, test stuff:

$ touch 1.png 2.png 3.png

Then:

for i in *.png ; do yes | rm -i $i 2>&1 >/dev/null | awk '{gsub(/^.|..$/,"",$NF);print $NF}' >> file ; done
$ cat file
1.png
2.png
3.png

or:

for i in *.png                                       # daloop
do                                                   # yes sir
  yes |                                              # nod to pipe
  rm -i $i 2>&1 >/dev/null |                         # rm interactively piping the stderr
  awk '{ gsub(/^.|..$/,"",$NF); print $NF }' >> file # ... to awk
done                                                 # phew

Quote $i if needed.

0
Adaleni On

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

0
hek2mgl On

Since you are on Windows (for whatever reason... ;) ) you may want to use -printf in order to produce Windows style line endings:

find . -name '*.png*' -delete -printf "%p\r\n" >> log.txt

Alternatively just configure the text editor you are using to view the output file to UNIX line endings.

To add a message:

find . -name '*.png*' -delete -printf "Deleted: %p\r\n" >> log.txt