Replace nth occurrence in filename

Advanced Renamer forum
#1 : 26/07-12 05:25
Ian
Ian
Posts: 8
Hi, I was wondering if its possible to replace an nth occurrence of a character or phrase in a filename. For example, replacing the third underscore from the beginning of "Test_Image_A_01.jpg" with a dash, would result in "Test_Image_A-01.jpg". If its not currently possible, then I think this would be a great tool to add on to the application, thanks in advance.


26/07-12 05:25
#2 : 27/07-12 10:31
Kim Jensen
Kim Jensen
Administrator
Posts: 883
Reply to #1:
If your files always have 4 words you can use the New Name method and use this pattern:
<Word:1>_<Word:2>_<Word:3>-<Word:4>
Remember to set Apply To to Name.



27/07-12 10:31
#3 : 29/07-12 04:08
Ian
Ian
Posts: 8
Reply to #2:
Thanks for the reply, but I was wanting to rename files with a variable length or pattern. I guess right now it doesn't seem to be possible. But as I said before, it would be a nice feature to find and replace a character with the option of only replacing from a certain place, maybe also having the option of starting backwards from the end, just like the renumbering method.


29/07-12 04:08
#4 : 30/07-12 20:28
Kim Jensen
Kim Jensen
Administrator
Posts: 883
Reply to #3:
You are right, there is no simple way of doing it with a variable length in AR at the moment. But there is a way to do it with the use of regular expressions. Add the replace method and configure it like this:

Text to be replaced: _([^_]*)$
Replace with: -\1
Case sensitive: off
Use regular expressions: on
Apply to: Name


30/07-12 20:28
#5 : 03/08-12 12:42
Stefan
Stefan
Posts: 274
Reply to #1:

QUOTE:
replacing the third underscore from the beginning
of "Test_Image_A_01.jpg" with a dash,
would result in "Test_Image_A-01.jpg".



FROM:
"Test_Image_A_01.jpg"
TO:
"Test_Image_A-01.jpg"
USE:
Script in 3.5 beta


Here is my first try for this
with less error handling
so please try with test files only.
Maybe someone got an better idea?




EDIT --- this code is buggy -- have to test some more. Sorry



[code]

// Find n'th occurrence of an sign
//////////////////////////////////


// User settings:
Sign = "_"; // sign to find
FindSignOccur = 3; // find n'th occurrence of this sign
ReplaceWith = "-"; // replace the found pos with this


// THE CODE:
// Find the pos of the n'th occurrence of the sign:
SignAmount = item.name.search(Sign);
StartIndex = 0;
var FOUND;

if(FindSignOccur <= SignAmount){
for( loop=1; loop <= FindSignOccur; loop++ ){
idx = item.name.indexOf(Sign, StartIndex);
StartIndex = idx +1;
}
FOUND = true;
}

if(FOUND){
//Compose the new file name:
P1_Before = item.name.slice(0,idx);
P2_ThePos = ReplaceWith;
P3_After = item.name.slice(idx +1);
P4 = item.extension;
FOUND = false; //clear for the next file!
return P1_Before + P2_ThePos + P3_After + P4;
}else{
//Return the original uncanged name:
return item.newName;
}

[/code]



03/08-12 12:42