我正在尝试删除字符串中的前导和尾随空格但是我正在使用的代码不起作用......如果我在开头或结尾处选择没有空格的目录路径,它仍然有效。我做错了什么?
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
答案 0 :(得分:3)
类似于double_j的answer,但是对于那些降落在这里的人来说......
我经常使用一个简单的子例程,使用echo " str1 " | xargs
shell脚本:
on trim(theText)
return (do shell script "echo \"" & theText & "\" | xargs")
end trim
或因为JavaScript是我在JS&amp;这样做(即使它非常低效,所以我不会将它用于trim
,但是当效率高的时候它可以很快赢得更复杂的东西。 #39; t critical):
on trim(theText)
return (do shell script "osascript -l JavaScript -e '\"" & theText & "\".trim()'")
end trim
(也许有一种真正的方式在AppleScript中执行内联JS,但我不确定...... yet)
答案 1 :(得分:2)
这是另一种更简单的方法:
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
答案 2 :(得分:1)
如果您想从字符串中修剪空格,下面的脚本应该这样做。但是,您的变量名称filePath让我相信您的输入是文件路径;)。如果是这种情况,路径的末尾将不会因为名称扩展而被修剪,并且除非您的驱动器名称以空格开头,否则不会修剪路径的开头。如果要查看文件名中的空格,则必须调整脚本。
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