Matt Hancock
Matt Hancock

Reputation: 4039

Fixed file name length of increasing numbers with bash

I have files with names fixed to 4 characters in length. They look like:

0000.png, 0001.png, ... , 0027.png, ..., etc...

They're increasing integers, 0, 1, ..., n. Zeros are padded to the additional space which the number itself does not fill so that the full file name is 4 characters.

In python, I can loop through these files with something like:

for i in range(n):
    file_name = '0'*(4-len(str(n))) + str(n) + '.png'

How do I achieve the same effect with bash? I'm not great with bash, so '0' padding part is throwing me off.

Upvotes: 0

Views: 409

Answers (3)

iruvar
iruvar

Reputation: 23384

You could also try globbing

for x in [[:digit:]][[:digit:]][[:digit:]][[:digit:]].png; 
do 
    echo "$x";
done

Upvotes: 1

Jahid
Jahid

Reputation: 22428

You can do this too:

n=5
for ((i=0;i<=n;i++)); do 
  filename=$(printf "%0.4d.png" $i)
  echo $filename
done

Upvotes: 1

Cyrus
Cyrus

Reputation: 88839

Try this:

n=5
for ((i=0;i<=$n;i++)); do 
  printf -v file_name "%0.4d.png" $i
  echo $file_name
done

Output:

0000.png
0001.png
0002.png
0003.png
0004.png
0005.png

Upvotes: 2

Related Questions