getting part of a filename..

hey,

im playing around with some applescripts and have a question.

ive got a file, say,

SP1324 oakland.pdf or #SP1234&SP1234 oakland.pdf

i want to rename it with some text in place of the numbers. in other words, the files would become “XXX oakland.pdf”

basically, i just need to know how to isolate the area of the filename that comes after the last integer, " oakland.pdf" in this case.

thanks guys! this site is amazing.

Hi,

assuming that there’s always a space character before the text to keep, something like this


set textToReplace to "XXX"
set theText to "SP1324 oakland.pdf"
set {TID, text item delimiters} to {text item delimiters, space}
set t2 to last text item of theText
set text item delimiters to TID
set newText to textToReplace & space & t2

Here’s another way and might work better if there’s not always a space character separating the numbers from the text you want to keep. Basically lastNumberIndex finds the index of the last number in the text, so we just get the rest of the text after the last number index and add XXX to it.

set theText to "#SP1234&SP1234 oakland.pdf"

set lastNumberIndex to 1
repeat with i from 1 to count of theText
	try
		(item i of theText) as number
		set lastNumberIndex to i
	end try
end repeat

set finalText to "XXX" & text (lastNumberIndex + 1) thru -1 of theText
--> XXX oakland.pdf

thats exactly what i needed. thanks again.

i hope one day to be able to answer some of the questions in this forum, but in the mean time, its just awesome being able to get things done here at work that nobody even thought possible.

you guys are a truly amazing resource.

Not sure which script you decided to go with, but you’re welcome any way. I started like you. I came here for help at first, loved the site, and eventually learned enough where I can help others. I hope you have the same experience.

I just had an idea how to make my above script more efficient. If you reverse the repeat loop checking the characters from the last to the first, you will know when you found the “last number” when you get the first positive hit if moving in reverse order. At that point you can stop the repeat loop because you found the “last number index”. The first way always queries every character but this new way will stop when it gets its first result. It’s probably not a big deal since the text is relatively small… but it is more efficient.

set theText to "#SP1234&SP1234 oakland.pdf"

set lastNumberIndex to 0
repeat with i from (count of theText) to 1 by -1
	try
		(item i of theText) as number
		set lastNumberIndex to i
		exit repeat
	end try
end repeat

set finalText to "XXX" & text (lastNumberIndex + 1) thru -1 of theText
--> XXX oakland.pdf