Automator用苹果脚本或shell脚本替换字符

时间:2013-08-28 13:20:32

标签: shell applescript automator

我正在创建一个automator进程,但我需要取字符串并用字符“/”替换所有“\”字符。与伙伴一起工作,我们决定使用shell脚本,但我愿意做任何事情。根据我们写的那行,我们只是得到一个错误。

set input to (do shell script "echo \"" & input & "\" | sed 's/\\\\//g'")

由于

3 个答案:

答案 0 :(得分:3)

尝试:

set myString to "This\\is\\my\\string" -- really This\is\my\string

set {TID, text item delimiters} to {text item delimiters, "\\"}
set myString to text items of myString
set text item delimiters to "/"
set myString to myString as text
set text item delimiters to TID

return myString

set input to "This\\is\\my\\string" -- really This\is\my\string
set output to do shell script "echo " & quoted form of input & " | sed 's/[\\]/\\//g'"

答案 1 :(得分:1)

据我所知it is no longer necessary to restore text item delimiters,所以adayzdone的例子可以简化为:

set s to "aa\\bb\\cc"
set text item delimiters to "\\"
set ti to text items of s
set text item delimiters to "/"
ti as text -- "aa/bb/cc"

do shell script使用/bin/sh,这是bash的一个版本,它以POSIX模式启动,并且还有一些其他更改。其中之一是默认启用xpg_echo,以便echo解释转义序列,如\t

do shell script "echo " & quoted form of "ss\\tt" & " | xxd -p" -- "737309740a"

您可以改为使用printf %s

do shell script "printf %s " & quoted form of "ss\\tt" & "|tr \\\\ /" -- "s/t"

如果你没有添加without altering line endings说明符,do shell script会将行结尾转换为CR,并从输出的末尾选择一个换行符。

答案 2 :(得分:0)

@Lauri Ranta的do shell script指针很有帮助,但原始命令的一个简单变体可以解决问题:

即使do shell script调用bash作为sh,因此在调用&#39; POSIX模式&#39;的模式下,仍有许多特定于bash的功能,其中所谓的 here-string 通过stdin将字符串直接提供给命令,例如:cat <<<'Print this'

因此,通过使用here-string - 从AppleScript传递quoted form of,这总是可取的 - 绕过echo问题:

# Sample input.
set input to "a\\\\b" # equivalent of" 'a\\b'

# Remove all `\` characters; returns 'ab'
set input to (do shell script "sed 's/\\\\//g' <<<" & quoted form of input)

替代方案,使用tr -d代替sed

 set input to (do shell script "tr -d '\\\\' <<<" & quoted form of input)