删除字符串中的前后空格:AppleScript [英] Remove preceding and trailing white spaces in string: AppleScript

查看:42
本文介绍了删除字符串中的前后空格: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

推荐答案

类似于 double_j 的 answer,但对于其他降落在这里...

Similar to double_j's answer, but for others who land here...

我经常使用一个简单的子程序,带有 echo " str1 " |xargs shell 脚本:

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 因为 JavaScript 是我的典型语言,我有时会在 JS &这样做(即使它非常低效,所以我不会将它用于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

(也许有一种真正的方法可以在 AppleScript 中执行内联 JS,但我不确定......尚未)

(Perhaps there's a real way to execute inline JS in AppleScript, but I'm not sure......yet)

这篇关于删除字符串中的前后空格:AppleScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆