简体   繁体   English

如何使用Shell脚本重命名所有文件?

[英]How to rename all the files using shell script?

I have hundreds of file of same format. 我有数百个相同格式的文件。 I want to rename the files by taking the first six characters and the extension. 我想通过使用前六个字符和扩展名来重命名文件。

Following code extracts the first 6 characters... I am displaying them 以下代码提取了前6个字符...我正在显示它们

     for i in *.png; do echo $i | awk '{ print substr($0, 0, 7 )}'; done

I am unable to concat the extension. 我无法连接该扩展名。 Could somebody help. 有人可以帮忙。 It will be great if the script could be completed with mv command. 如果脚本可以用mv命令完成,那就太好了。

Thanks 谢谢

假设每个文件名在扩展名前至少包含六个字符,则可以编写

for file in *.png ; do mv "$file" "${file:0:6}.png" ; done

Do the piping outside the loop body, if you continue to use awk : 如果继续使用awk ,请在循环体外进行配管:

for i in *.png; do echo $i; done |
awk '{ print "mv $0 " substr($0, 0, 7) ".png"}' |
sh -vn

The revised awk prints the mv commands. 修改后的awk打印mv命令。 When you're happy it is going to do the right job, replace the -vn with -x (or with nothing). 当您感到满意时,它将做正确的工作,将-vn替换为-x (或什么都不做)。

This will work with pretty much any shell. 这几乎适用于任何外壳。 If you're using bash specifically, then there are built-in string manipulations to do the job you need - see the answer by ruakh for one possible technique. 如果您专门使用bash ,则可以使用内置的字符串操作来完成所需的工作-请参阅ruakh的答案以了解一种可能的技术。 There are a myriad other options available; 还有许多其他选择。 some systems have a capable rename command (others have a less capable version). 一些系统具有功能强大的rename命令(其他系统具有功能较弱的版本)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM