Search code examples
applescript

Remove preceding and trailing white spaces in string: AppleScript


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

Solution

  • 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