I'm trying to remove preceding and trailing white spaces in a string but the code I'm using isn't working... It still only works if I select a directory path without white spaces at the beginning or the end. What am I doing wrong?
on run {input, parameters}
set filePath to input
set ASTID to AppleScript's AppleScript's text item delimiters
set AppleScript's text item delimiters to space
set unwantedSpaces to filePath's text items
set a to 1
set b to (count unwantedSpaces)
repeat while (a < b) and ((count item a of unwantedSpaces) is 0)
set a to a + 1
end repeat
repeat while (b > a) and ((count item b of unwantedSpaces) is 0)
set b to b - 1
end repeat
set strippedText to text from text item a to text item b of filePath
set AppleScript's AppleScript's text item delimiters to ASTID
set validFilePaths to {}
repeat with aLine in strippedText
try
set targetAlias to POSIX file aLine as alias
tell application "Finder" to reveal targetAlias
set end of validFilePaths to {}
end try
end repeat
return validFilePaths
end run
Similar to double_j's answer, but for others who land here...
I often use a simple sub-routine, with echo " str1 " | xargs
shell script:
on trim(theText)
return (do shell script "echo \"" & theText & "\" | xargs")
end trim
OR because JavaScript is my typical language I sometimes think in JS & do this (even though it's terribly inefficient, so I wouldn't use this for trim
but it can be a quick win for more complex things when being efficient isn't critical):
on trim(theText)
return (do shell script "osascript -l JavaScript -e '\"" & theText & "\".trim()'")
end trim
(Perhaps there's a real way to execute inline JS in AppleScript, but I'm not sure......yet)
Here's another simpler approach:
on run {input, parameters}
set filePath to input as text
set Trimmed_filePath to do shell script "echo " & quoted form of filePath & " | sed -e 's/^[ ]*//' | sed -e 's/[ ]*$//'"
end run
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With