4

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
sbaden
  • 555
  • 3
  • 16
  • 30

5 Answers5

4

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)

Community
  • 1
  • 1
brandonjp
  • 3,018
  • 2
  • 28
  • 27
3

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
double_j
  • 1,636
  • 1
  • 18
  • 27
  • Many people don't find regex simpler. Also, you don't need to pipe the output if you are using -e. set endString to do shell script "sed -Ee 's/^[ ]+//' -e 's/[ ]+$//' <<< " & quoted form of filePath – adayzdone Dec 05 '14 at 21:14
  • @adayzdone I appreciate your feedback. I'd still go with mine because its about 1/10th the code. And seems more efficient. – double_j Dec 05 '14 at 22:26
  • 1
    It is less code... but not as efficient/fast. https://gist.github.com/anonymous/e227ae8672e19019a526 – adayzdone Dec 05 '14 at 22:40
  • @adayzdone I'm impressed. 20 milliseconds faster, +1 for that :) I have to say though if this were a large file or list, then sed and or perl has to be faster right? – double_j Dec 05 '14 at 22:49
  • I'd be interested in seeing the results. Update the variable and let me know. – adayzdone Dec 05 '14 at 22:59
  • @adayzdone So if your working with a file with multiple lines, after about 500 lines my method becomes the better option just because you can feed the file straight into sed and its more powerful with things like that. If you're working with smaller data set, yours is the right way. – double_j Dec 06 '14 at 00:32
  • I'm surprised because the loop exits after the first non-whitespace character. [ Start...1 line] should exit at the same point as [ Start...100000 lines] because the S exits the loop. Thanks for following up. – adayzdone Dec 06 '14 at 01:33
  • @adayzdone It was done on a loop. Modified the script a little – double_j Dec 06 '14 at 04:47
2

If you are looking to trim spaces from a string, the script below should do it. However, your variable name filePath leads me to believe that your input is a file path ;) . If this is the case, the end of the path won't be trimmed because of the name extension and the beginning of the path won't be trimmed unless your drive's name starts with a space. If you are looking to trim spaces in a file name, you will have to adjust the script.

on run {input, parameters}
    set filePath to (input as text)
    return my trim(filePath, true)
end run

-- From Nigel Garvey's CSV-to-list converter
-- http://macscripter.net/viewtopic.php?pid=125444#p125444
on trim(txt, trimming)
    if (trimming) then
        repeat with i from 1 to (count txt) - 1
            if (txt begins with space) then
                set txt to text 2 thru -1 of txt
            else
                exit repeat
            end if
        end repeat
        repeat with i from 1 to (count txt) - 1
            if (txt ends with space) then
                set txt to text 1 thru -2 of txt
            else
                exit repeat
            end if
        end repeat
        if (txt is space) then set txt to ""
    end if

    return txt
end trim
adayzdone
  • 11,120
  • 2
  • 20
  • 37
  • It is a file path but it is a file path that has been copied and pasted into a word doc or email. The idea is that someone would be able to select the path, right-click, choose service and then this applescript. This script would then take the selected string and locate the file in the Finder. I'm noticing though that if I triple click on the string and select the entire line rather than just the string itself it doesn't work because of the extra empty characters/white spaces. Will this script work for this scenario? It needs to leave the spaces in the file path alone. – sbaden Dec 05 '14 at 01:50
1

This is my solution for trimming leading/trailing characters. This runs entirely inside AppleScript.

-- trim specified leading/trailing characters from a string
on trimString(theSource, theTrimmer)
    local theResult
    
    set strBegin to 1
    set strEnd to length of theSource
    
    -- find first char after theTrimmer
    if theSource starts with theTrimmer then
        repeat while ((strBegin < strEnd) and (item strBegin of theSource is theTrimmer))
            set strBegin to strBegin + 1
        end repeat
    end if
    
    -- find last char before theTrimmer
    if theSource ends with theTrimmer then
        repeat while ((strEnd > strBegin) and (item strEnd of theSource is theTrimmer))
            set strEnd to strEnd - 1
        end repeat
    end if
    
    set theResult to characters strBegin thru strEnd of theSource as string
    if theResult = theTrimmer then
        return ""
    else
        return theResult
    end if
end trimString
on run
   set myStr to "......this is a string..."
   set trimmed to trimString(myStr,".")
end run
1

NSString in the Foundation Framework provides an dedicated API for that purpose

use AppleScript version "2.5"
use framework "Foundation"

set theText to "    Hello World!   "
set nsText to my (NSString's stringWithString:theText)
set trimmedText to (nsText's stringByTrimmingCharactersInSet:(my NSCharacterSet's whitespaceCharacterSet())) as text
-- "Hello World!"
vadian
  • 274,689
  • 30
  • 353
  • 361