Linux shell script to add leading zeros to file names

Try:

for a in [0-9]*.txt; do
    mv $a `printf %04d.%s ${a%.*} ${a##*.}`
done

Change the filename pattern ([0-9]*.txt) as necessary.


A general-purpose enumerated rename that makes no assumptions about the initial set of filenames:

X=1;
for i in *.txt; do
  mv $i $(printf %04d.%s ${X%.*} ${i##*.})
  let X="$X+1"
done

On the same topic:

Leave a Comment