How to delete all files with certain suffix before file extension

那年仲夏 提交于 2019-12-11 22:21:59

问题


I was just handed a directory with some 40,000+ images, and the directory includes three versions of every file, which makes it a bear to have to transfer between servers.

I'm looking for a way using bash (OSX Terminal) to find and remove (rm) all files, for example, with _web, or _thumb on the end of the filename, just before the .jpg (or .gif, or .png, or .bmp, etc.) extension.

So, to be clear, I have the following files:

1.jpg
1_web.jpg
1_thumb.jpg
2.gif
2_web.gif
2_thumb.gif
etc.

And I only want "1.jpg", "2.gif", etc. to remain.

I've been able to rename extensions in the past, but my command-line-fu is pretty weak, and I'm at my wits end trying to figure out something that's reusable (I'm going to need to do this a couple times, as I'm working on a continuous migration script for this project).

Edit: After a bit more work on this, I found a few odd limitations of rm and xargs that I had to work around. I basically adapted the accepted answer below and ended up with:

$ find . -name '*_thumb.*' -print0 | xargs -0 rm -f
$ find . -name '*_web.*' -print0 | xargs -0 rm -f

Now I'm down to about 10,000 files - quite a savings in terms of pushing files around on the web!


回答1:


One (relatively robust) option is to run

find . -iregex ".*\(_web\|_thumb\)\.\(jpg\|png\|bmp\)" -delete

Assuming that you don't have anything other than image files in the directory, another (simpler) option is to run

 rm *_web.* *_thumb.*

Warning: this will also delete files that are named something like my_web.file.jpg, so if you want to play safe, you'll have to add all the extensions instead of relying on .* If you know that your extensions are always going to be 3 characters long, you can use something like *_thumb.???




回答2:


I don't have a MAC or a UNIX terminal in front of me, but I imagine something like the following might work

rm *_web.jpg
rm *_web.jpg
rm *_thumb.gif


来源:https://stackoverflow.com/questions/6839966/how-to-delete-all-files-with-certain-suffix-before-file-extension

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