如何删除文件扩展名前带有特定后缀的所有文件
我刚刚收到一个包含大约 40,000 多个图像的目录,该目录包含每个文件的三个版本,这使得在服务器之间传输变得很困难。
我正在寻找一种使用 bash (OSX 终端)查找并删除 (rm) 所有文件的方法,例如,在文件名末尾使用 _web 或 _thumb,就在 .jpg (或 .gif、或 . png 或 .bmp 等)扩展名。
所以,要明确的是,我有以下文件:
1.jpg
1_web.jpg
1_thumb.jpg
2.gif
2_web.gif
2_thumb.gif
etc.
我只想保留“1.jpg”、“2.gif”等。
我过去能够重命名扩展,但是我的命令行fu非常弱,而且我在试图找出可重用的东西时束手无策(我需要这样做几次次,因为我正在为该项目编写持续迁移脚本)。
编辑:经过更多的工作,我发现了 rm 和 xargs 的一些奇怪的限制,我必须解决这些限制。我基本上改编了下面接受的答案并最终得到:
$ find . -name '*_thumb.*' -print0 | xargs -0 rm -f
$ find . -name '*_web.*' -print0 | xargs -0 rm -f
现在我的文件数量减少到了大约 10,000 个 - 在网络上推送文件方面节省了相当多的钱!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个(相对稳健的)选项是运行
假设目录中除了图像文件之外没有任何其他内容,另一个(更简单的)选项是运行
警告:这也会删除名为 my_web.file.jpg 的文件,所以如果你想安全起见,你必须添加所有扩展名而不是依赖 .*
如果你知道你的扩展名总是 3 个字符长,你可以使用像 *_thumb 这样的东西。???
One (relatively robust) option is to run
Assuming that you don't have anything other than image files in the directory, another (simpler) option is to run
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.???
我面前没有 MAC 或 UNIX 终端,但我想像下面这样的东西可能会起作用
I don't have a MAC or a UNIX terminal in front of me, but I imagine something like the following might work