Shell script-Batch rename

Source: Internet
Author: User

If you have a small requirement at work, you need to rename a series of files.

The original format is string_1.obj. Now you want to change the number in the file name to a fixed length. If the number is less than the number of digits, it is changed to string_001.obj.

I learned to write a script. It's a good dish. I 'd like to post it for your advice.

#! /bin/bash# this script is used to rename files# the orignal filename is as XXXX_1.obj# and the final filename is as XXX_0001.obj the width of the num  is given as a parameterrm result.txtexport suffix=".obj"find . -name "*$suffix" > result.txtcat result.txt | while read onelinedoexport orifilename=${oneline##*/}    #cut off the path of filenameexport prefilename=${orifilename%_*} #without "_"export numfilename=${oneline##*_}export numfilename=${numfilename%.*} #get the num in filename((i=$1-${#numfilename})) #get the num of zero which is  neededexport zeros=`echo $numfilename | awk '{printf "%0'"$i"'d",0}{print}'` export finalfilename=$prefilename"_"$zeros$suffix#echo "$orifilename, $finalfilename"#rename "s/$orifilename/$finalfilename/" ./$finalfilenamemv $orifilename $finalfilenamedoneecho "Done"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.