Search code examples
regexmacosterminalbatch-processing

Batch rename files by adding +1 to prefix number in a filename


So, my question is: How to add +1 to the prefix number in a filename?

The goal is to go rename multiple files so that they go from this:

1_loremipsum_and_stuff_2013.pdf
2_loremipsum_and_stuff_2013.pdf
3_loremipsum_and_stuff_2013.pdf
4_loremipsum_and_stuff_2013.pdf
13_loremipsum_and_stuff_2013.pdf
18_loremipsum_and_stuff_2013.pdf
19_loremipsum_and_stuff_2013.pdf
20_loremipsum_and_stuff_2013.pdf

To this:

2_loremipsum_and_stuff_2013.pdf
3_loremipsum_and_stuff_2013.pdf
4_loremipsum_and_stuff_2013.pdf
5_loremipsum_and_stuff_2013.pdf
14_loremipsum_and_stuff_2013.pdf
19_loremipsum_and_stuff_2013.pdf
20_loremipsum_and_stuff_2013.pdf
21_loremipsum_and_stuff_2013.pdf


I'm not very experienced with terminal at all. I was able to find examples for removing prefix number. It works fine, but when I try to replace something by using regex, I can't get very close.

So after first trying and failing horribly at correctly regexing this in the terminal, I thought I'd give it a try in javascript.

I was able to get it working in javascript /[0-9]*(?=_)/.

So, my best guess for terminal is this, except it doesn't quite work.:

cd  {TESTFOLDER}

REGEX=[0-9]*(?=_)

for name in *; do mv -v "$name" "${name/$REGEX/$(( ${name/$REGEX}+1 ))}"; done

Solution

  • Using BASH string manipulation:

    s='1_loremipsum_and_stuff_2013.pdf'
    mv "$s" "$((${s%%_*}+1))_${s#*_}"
    

    EDIT: Based on discussion below you can use

    while read f; do 
       mv "$f" "$((${f%%_*}+1))_${f#*_}"
    done < <(sort -t_ -rnk1,2 <(printf "%s\n" *_*))