简体   繁体   中英

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

     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.

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 :

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. When you're happy it is going to do the right job, replace the -vn with -x (or with nothing).

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. There are a myriad other options available; some systems have a capable rename command (others have a less capable version).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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