Renaming Files, part 2

Interestingly enough, I helped a person via a forum to preform a similar task. The problem was very similar, though I actually misunderstood it at first.

He had:

S0001moretext.jpg
S0012moretext.jpg
S0123moretext.jpg
S1234moretext.jpg

And wanted to end up with:

S1moretext.jpg
S12moretext.jpg
S123moretext.jpg
S1234moretext.jpg

At first I assumed that the series was supposed to be in sequential order and posted nearly the same script I used in my previous post.

i=0; for file in *; do let i+=1; mv "$file" "S${i}${file:5}"; done

But he actually wanted the zeros removed from the filenames only. So I wrote a new script to accomplish that task. It removes all the zeros in the filename where ever and in whatever quantity they occur.

for file in *; do mv "$file" "`echo "$file" | tr -d '0'`"; done

Once again, it seems I misunderstood the problem! /sigh. I blame my dog for always begging me to take him to the dog park or on walks in the woods. The “moretext.jpg” in the filenames from above actually contains the year the image was created in. Thus the problem is actually to go from this:

S0001moretext2012.jpg
S0012moretext2013.jpg
S0123moretext2014.jpg
S1234moretext2015.jpg

To this:

S1moretext2012.jpg
S12moretext2013.jpg
S123moretext2014.jpg
S1234moretext2015.jpg

That’s a little harder, but still an easy script since it follows well known rules where the zeros to be removed are only contained withing the first five characters of the filename.

The one-line script is kind of ugly (as is the following “pretty” version — I’m absolutely sure there is an elegant way to do this, but quite frankly I didn’t have the time to find it).

The one liner that removes all zeros that occur within the first five characters of the filename and otherwise leave the result of the filename unchanged.

for file in *; do for (( i=0; i<6; i++ )); do if [[ ${file:$i:1} == [1-9] || $i == 5 ]]; then start="$(echo "${file:0:$i}" | tr -d '0')"; end="${file:$i}"; mv "$file" "$start$end" 2> /dev/null; break; fi; done; done

And for the not-so-pretty, pretty version:

#!/bin/bash
for file in *
do
     for (( i=0; i<6; i++ ))
     do
          if [[ ${file:$i:1} == [1-9] || $i == 5 ]]
          then
               start="$(echo "${file:0:$i}" | tr -d '0')"
               end="${file:$i}"
               mv "$file" "$start$end" 2> /dev/null
               break
          fi
     done
done

In the end, I guess it doesn’t matter what it looks like so long as it works. At least until I show it on a blog lol.

Tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

Protected by WP Anti Spam