Beginners question: Split a string in AppleScript


I have a string (“local path/folder/file.txt”) and now i want to retreive the string “file”.

How do i spit the first string so i get only the second string

Are you saying that you want to extract the file’s name from the string?

– Rob

You can use this:

text 1 thru 4 of "Hello, Dolly"
--> "Hell"

Which is better and quicker than:

characters 1 thru 4 of "Hello, Dolly"
--> {"H", "e", "l", "l"}
characters 1 thru 4 of "Hello, Dolly" as text
--> "Hell"

You can also pick “words” from a string:

word 2 of "Helly, Dolly"
--> "Dolly"

And “paragraphs”:

set longText to "Hello, Dolly
My name is Lucas.
Do you wanna dance?"
paragraph 2 of longText
--> "My name is Lucas."

Hi :slight_smile:

Here one suggestion :

set Txt1 to "local path/folder/file.txt"
set Txt2 to "file"

set LengthTxt2 to length of Txt2 --> 4
set PlaceTxt2 to offset of Txt2 in Txt1 --> 19

set TxtOk to (text PlaceTxt2 thru (PlaceTxt2 + LengthTxt2 - 1) of Txt1) --> "file"
--> set TxtOk to (text 19 thru (19 + 4 - 1) of Txt1) --> "file"

With “offset” propertie, you can know the place of one string in another text…

Using AppleScrpt’s text item delimiters (do a web search) is always a good choice for splitting up a string of abritrary length, especially if you don’t knwo the name of the file. You may have to use it a second time to remove the file extension.

Don’t forget that you can also use negative indices to work from the end of a list:

set theString to "hello world"
text 1 through 4 of theString
--> "hell"
text -1 through -4 of theString
--> "orld"

As plaid suggested, text item delimiters is another way of doing this and is especially useful when you don’t know the length/offsets of the string in question:

set inputStr to "path/to/some/file.txt"
set oldDelims to my text item delimiters -- save the current delimiters
set my text item delimiters to "/" -- the character to split on
set filename to last text item of inputStr -- 'text item' now refers to the string broken on the 'text item delimiters'
--> "file.txt"
set my text item delimiters to oldDelims -- just to be safe, restore the old delimiters

In this particular case, though, if you’re dealing with files that already exist you can ask the Finder to take care of this for you:

set inputFile to "/path/to/file.txt"
set theFile to POSIX file inputFile as alias
tell application "Finder" to set filename to name of theFile
--> "file.txt"

This latter approach has the advantage of being able to use the Finder’s file manipulation abilities to munge the file (extract the filename extension, for example), but it won’t work if the file doesn’t exist whereas the ‘text items’ or ‘offset’ methods are working purely with strings and therefore don’t have any such limitations.