Renaming files in lexicographical order with a numerical pattern that increases sequentially with fixed padding

You can use the l parameter expansion flag to pad a number on the left.

i=0; for x in *; do ((++i)); mv -- $x new/${(l:6::0:)i}; done

There is a relatively simple way to do this with only POSIX features: start numbering at 1000001 (for 6 digits) instead of 1, and strip off the leading 1. It is less straightforward but a few characters shorter.

i=1000000; for x in *; do i=$((i+1)); mv -- "$x" new/${i#1}; done

If you want to take advantage of zmv, you can use an arithmetic expression that increments i inside the replacement text.

i=0; zmv '*' '${(l:6::0:)$((++i))}'
i=1000000; zmv '*' '${$((++i))#1}'

Add the o glob qualifier if you need to sort the files in a different order. With zmv, you need to pass the -Q flag when the pattern contains glob qualifiers.


Use this bash snippet.

[centos@centos new]$ touch a bb ccc dddd eee f gh i
[centos@centos new]$ touch abc emrls cdg sf
[centos@centos new]$ touch ABC A BB CCC DD GI KLM kmna kabc mas nas san fin zoo
[centos@centos new]$ \ls -1
a
A
abc
ABC
bb
BB
ccc
CCC
cdg
DD
dddd
eee
emrls
f
fin
gh
GI
i
kabc
KLM
kmna
mas
nas
san
sf
zoo
[centos@centos new]$ a=0; for i in *; do a=$(($a+1));  b=`printf "%06d" $a`; mv -v ${i} ${b};  done
`a' -> `000001'
`A' -> `000002'
`abc' -> `000003'
`ABC' -> `000004'
`bb' -> `000005'
`BB' -> `000006'
`ccc' -> `000007'
`CCC' -> `000008'
`cdg' -> `000009'
`DD' -> `000010'
`dddd' -> `000011'
`eee' -> `000012'
`emrls' -> `000013'
`f' -> `000014'
`fin' -> `000015'
`gh' -> `000016'
`GI' -> `000017'
`i' -> `000018'
`kabc' -> `000019'
`KLM' -> `000020'
`kmna' -> `000021'
`mas' -> `000022'
`nas' -> `000023'
`san' -> `000024'
`sf' -> `000025'
`zoo' -> `000026'
[centos@centos new]$