Edit up top: The accepted answer works splendidly except I had to add //ToExpression
to the end of the definition of ns
given by the submitter. Without this, the numbers were not actually being treated as numbers by Mathematica.
Original Question Follows:
Sorry for the very verbose title, but I couldn't think a very succinct way to put it. I have a list of file names:
samplenames = {"FileName(2).csv", "FileName(3).csv",
"FileName(4).csv", "FileName(10).csv", "FileName(15).csv",
"FileName(16).csv", "FileName(17).csv", "FileName(18).csv",
"FileName(25).csv", "FileName(30).csv", "FileName(31).csv"};
I would like some code to take these and rename them so that the output is
{"NewName1(1).csv", "NewName1(2).csv", "NewName1(3).csv",
"NewName2(1).csv", "NewName3(1).csv", "NewName3(2).csv",
"NewName3(3).csv", "NewName3(4).csv", "NewName4(1).csv",
"NewName5(1).csv", "NewName5(2).csv"}
So you can see what happens: The number in parentheses is incremented starting from 1 until there is a jump in the original list of file names. At this point, the number NOT in parentheses is incremented by 1 in the new name and the number in parentheses restarts from 1 again. To make the language easier to follow, let's call the two forms "FileName(i).csv" and "NewNamej(k).csv".
I can imagine there's some way to do this by splitting the list of file names using Split, maybe in a way similar to the "Split at Jumps" example found in the documentation (although I'm not familiar with working with strings), and then using the index of the sublist to determine j. The index within each sublist could be used to determine k. Of course, there may be far better ways to do it and I am open to any solutions.
I have almost no experience with string manipulation in Mathematica so the syntax is a little scary for me right now. I would greatly appreciate as much detail as possible about what is going on in any suggested solutions.
Lastly, I'd be willing to forgo the full version of what I'm asking for, as long as I could just batch rename any directory of files of the form "FileName(i).csv" to "NewName(j).csv" where j starts from 1 and increases in increments of 1 regardless of where i starts from and how it increments. Figure I'd ask for the stars first though :)
SortBy[..., StringLength]
will put shorter ones first - so 2 will come before 10, assuming all other parts of the name are the same. $\endgroup$