0

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.

Mona Jalal
  • 4,545
  • 21
  • 68
  • 99

2 Answers2

1

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;
Kulfy
  • 17,696
1

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.