Find and rename all pictures with incorrect file extension

走远了吗. 提交于 2019-12-24 03:23:30

问题


I'm looking for a way to automate renaming all images with a wrong filename extension. So far I at least found out how to get the list of all these files:

find /media/folder/ -name *.jpg -exec file {} \; | grep  'PNG\|GIF' > foobar.txt
find /media/folder/ -name *.png -exec file {} \; | grep 'JPEG\|GIF' >> foobar.txt
find /media/folder/ -name *.gif -exec file {} \; | grep 'JPEG\|PNG' >> foobar.txt

However, I would also like to automate the renaming. I tried things like

find /media/folder/ -name *.jpg -exec file {} \; | grep -l PNG | rename s/.jpg/.png/

but in this case grep -l or grep -lH don't list only filenames like I thought they would.


回答1:


The -l and -H flags of grep are not useful in your example. These flags have no effect when used with the standard input, like in your example coming from the pipe. These flags only work if you specify files (or directories and the -r flag for recursion), for example:

grep -rl PNG path/to/dir1 file2 file3

In your example the -l has no effect, so the output is the complete lines that matched PNG, which in your example probably look something like this:

icon.png: PNG image, 512 x 512, 8-bit/color RGBA, non-interlaced

To get only the filename, maybe you can cut off everything after the colon like this:

find /media/folder/ -name *.jpg -exec file {} \; | grep PNG | sed -e s/:.*// | rename s/.jpg/.png/


来源:https://stackoverflow.com/questions/15180099/find-and-rename-all-pictures-with-incorrect-file-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!