How can I get just the name of a file without the extension? If I use
set theName to (text 1 thru ¬
(offset of “.” in theFile) of theFile)
with say file ‘123.jpg’ I get ‘123.’ I want just 123 without the “.”
Thanks.
Pedro
How can I get just the name of a file without the extension? If I use
set theName to (text 1 thru ¬
(offset of “.” in theFile) of theFile)
with say file ‘123.jpg’ I get ‘123.’ I want just 123 without the “.”
Thanks.
Pedro
Here’s a handy subroutine by jobu. Although there might be an easier way to do it.
on removeExtension(this_name)
if this_name contains "." then
set delim to AppleScript's text item delimiters
set AppleScript's text item delimiters to "."
set cleanName to (text items 1 through -2 of (this_name as string) as list) as string
set AppleScript's text item delimiters to delim
return cleanName
else
return this_name
end if
end removeExtension
Then you can use it like this:
set theFile to "picture.jpg"
removeExtension(theFile)
--returns "picture"
That works if there are no other periods in the file name; eg, “picture01.jpg” works but “picture.01.jpg” does not. Also, the file name doesn’t always display the extension, even tho it’s there, and extensions may or may not be correctly set, or might be three or four characters, etc…
More robust routine to handle different file name/type conditions that might come up is:
on removeExtension(theFile) --where 'theFile' is an alias
set fileInfo to (info for theFile)
set fileName to fileInfo's displayed name
set fileExt to "." & (fileInfo's name extension) as string
if fileName ends with fileExt then ¬
return characters 1 thru ((offset of fileExt in fileName) - 1) ¬
of fileName as string
return fileName
end removeExtension
Tho you’ll need to pass it an alias to a file, not just a file’s name.
I use this, the parameter can be a string path, alias or Finder file specifier
on removeExtension(f)
set {name:Nm, name extension:Ex} to info for f as alias
if Ex is missing value then return Nm
return text 1 thru ((count Nm) - (count Ex) - 1) of Nm
end removeExtension
I like this short version. If there is no extension it still works and it ignores periods in the name.
set f to (choose file) -- for illustration
tell (info for f) to set {Nm, Ex} to {name, name extension}
set BN to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
BN