Shell – renaming multiple files increment order

renamescriptingshell

I have the following files

SSt12.precip.374.sub.climatology.ctl
SSt12.precip.2874.sub.climatology.ctl
SSt12.precip.3764.sub.climatology.ctl
SSt12.precip.6774.sub.climatology.ctl

I want to rename the files as

SSt12.precip.1.sub.climatology.ctl
SSt12.precip.2.sub.climatology.ctl
SSt12.precip.3.sub.climatology.ctl
SSt12.precip.4.sub.climatology.ctl

Best Answer

With zsh:

$ autoload zmv
$ n=0; zmv -n '(*.)<->(*.ctl)(#qn)' '$1$[++n]$2'
mv -- SSt12.precip.374.sub.climatology.ctl SSt12.precip.1.sub.climatology.ctl
mv -- SSt12.precip.2874.sub.climatology.ctl SSt12.precip.2.sub.climatology.ctl
mv -- SSt12.precip.3764.sub.climatology.ctl SSt12.precip.3.sub.climatology.ctl
mv -- SSt12.precip.6774.sub.climatology.ctl SSt12.precip.4.sub.climatology.ctl

(do it again without the -n to actually perform the renaming).

With GNU tools and assuming filenames don't contain newline characters, you could do:

ls -v | awk -F. -vOFS=. -vORS='\0' '/\.ctl$/{print;$3=++n;print}' |
  xargs -r0n2 echo mv --

(remove the echo to actually do the renaming)

Related Question