在命令行和Xargs中批量重命名文件 [英] Batch renaming files in command line and Xargs

查看:962
本文介绍了在命令行和Xargs中批量重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下结构:

.
..
a.png
b.png 
c.png

我运行了一个命令来调整它们的大小

I ran a command to resize them

ls | xargs -I xx convert xx -resize xx.jpg

现在我的目录看起来像这样

Now my dir looks like this

.
..
a.png.jpg
a.png
b.png.jpg
b.png
c.png.jpg
c.png



<一个扩展。不是两个。 (基本上,我如何清除我的原始错误)?


第二个问题是,在将来,使用xargs,如何更改文件的扩展名simular到第二个命令

The firs question is, how do i rename the file so that I can just have one extension. Not two. (basically, how do I clean up my original mistake)?

The second question is, in the future, using xargs, how do I change the extension of the file simular to second command?

推荐答案


如何重命名文件,以便我只能有一个扩展名。 p>

how do i rename the file so that I can just have one extension.



cd dir/with/messedup/files

for file in *.png.jpg; do
  mv "$file" "${file%.png.jpg}.jpg"
done




使用xargs,如何将文件扩展名修改为第二个命令?

in the future, using xargs, how do I change the extension of the file simular to second command?

据我所知,这是不可能做到的。最好的方法是使用一个类似上面的参数替换的for循环:

To my knowledge, that can't be done. The best way to do it would be to use a for-loop with parameter substitution much like the one above:

for file in *.png; do
  convert "$file" -resize "${file%.png}.jpg"
done

如果您有要转换的子目录中的文件,则可以在读 c时将找到 $ c> loop:

If you have files in subdirectories that you want converted, then you can pipe find to a while read loop:

find . -type f -name '*.png' |
while read file; do
  convert "$file" -resize "${file%.png}.jpg"
done

注意 :通常被认为是糟糕的主意使用shell脚本中的 ls 输出。虽然你的例子可能工作正常,有很多的例子,它不是。例如,如果你的文件名中有换行符(unix允许), ls 可能不会逃脱那些。 (这实际上取决于你的实现,这是不在脚本中使用 ls 的另一个原因;它的行为从一个框到下一个框很大)。你会得到更一致如果您在while中使用 find 循环或文件globbing(例如 *。png

NOTE: It's generally considered a bad idea to use the output of ls in a shell script. While your example might have worked fine, there are lot's of examples where it doesn't. For instance, if your filenames happened to have newlines in them (which unix allows), ls probably won't escape those for you. (That actually depends on your implementation, which is another reason not to use ls in scripts; it's behavior varies greatly from one box to the next.) You'll get more consistent results if you either use find in a while-read loop or file globbing (e.g. *.png) in a for loop.

这篇关于在命令行和Xargs中批量重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆