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,299
  • 20
  • 64
  • 96
  • 1
    Maybe use `find` command and its `exec` ? – Michal Przybylowicz Nov 10 '19 at 18:21
  • 1
    This answer [Renaming hundreds of files at once for proper sorting](https://askubuntu.com/a/473355/178692) uses the Perl-based `rename` with a simple shell glob - that avoids having to *generate* filenames – steeldriver Nov 10 '19 at 18:32
  • 1
    Use "if" to check if the file exists. `for n in $(seq 9); do if [[ -f $n.JPEG ]]; then mv $n.JPEG 0$n.JPEG; fi done;`. – Kulfy Nov 10 '19 at 18:32

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,416
  • 26
  • 64
  • 103
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.