Reputation: 903
So I have a string but I only want it after a certain part. I know that you would optimally do this in shell so I tried, but my limited shell knowledge didn't bring me far. This post tries to do a similar thing but not exactly what I need.
set theString to "hello/world"
do shell script "echo " & theString & "???"
return theString --the output should be hello
Upvotes: 1
Views: 2178
Reputation: 3142
This also works.
set theString to "hello/world"
set firstWord to 1st word of theString
return firstWord
OR
If there are any other characters and including “/“ in theString
, the following should take care of that.
set theString to "hello/world"
set firstWord to 1st word of (do shell script "echo " & ¬
quoted form of theString & " | sed -E 's@[^[:alpha:]]{1,}@ @'")
return firstWord
Upvotes: 1
Reputation: 7555
You can also use AppleScript's text item delimiters:
set theString to "hello/world"
set {TID, AppleScript's text item delimiters} to ¬
{AppleScript's text item delimiters, "/"}
set theString to first text item of theString
set AppleScript's text item delimiters to TID
do shell script "echo " & theString's quoted form & "???"
Returns:
hello???
However, return theString
after processing with AppleScript's text item delimiters will just return hello
in this use case.
Note the use of 's quoted form
in theString's quoted form
with the variable in the do shell script
command, as you should always quote what's being passed to the shell. You can also use this form: quoted form of theString
As you can see the offset of method presented in one of the other answers is more straight forward, however I've added this as an answer so you know what your other options are.
Upvotes: 1
Reputation: 285069
There's no shell script needed. Get the position of the slash in the string and return the substring from the beginning to the position - 1
set theString to "hello/world"
set slashIndex to offset of "/" in theString
return text 1 thru (slashIndex - 1) of theString
Upvotes: 4