zero padding of file names

I want to do zero-padding for names of files. what should I do if not all images exist like 1.JPEG doesn't exist or 99.JPEG or 110.JPEG ?

 $ for n in $(seq 9); do mv $n.JPEG 0$n.JPEG; done; mv: cannot stat ‘1.JPEG’: No such file or directory

I do not want to rename manually because order of videos are important.

3

2 Answers

You can use if inside the loop to check if the file exists. And if it does, then only mv operation would take place.

for n in $(seq 9)
do if [[ -f $n.JPEG ]] then mv $n.JPEG 0$n.JPEG fi
done;

Or in one line:

for n in $(seq 9); do if [[ -f $n.JPEG ]]; then mv $n.JPEG 0$n.JPEG; fi done;

Using parameter expansion you can split the filename into name and extension, then glue them together with printf formatting

#!/bin/bash
for i in *; do mv $i $(printf %04d.%s\\n ${i/./ })
done

printf formatting:

  • %04d pad digit with four zeros.
  • %s     String of characters.

${parameter/pattern/string}

  • Pattern substitution; parameter is expanded and the longest match of pattern against its value is replaced with string.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like