【发布时间】:2018-03-28 12:57:15
【问题描述】:
我在尝试从 Apple 脚本执行 shell 脚本时遇到问题。我做了一个“grep”,但一旦它包含特殊字符,它就不能按预期工作。 (该脚本读取目录中的子文件夹列表并检查是否有任何子文件夹出现在文件中。)
这是我的脚本:
set searchFile to "/tmp/output.txt"
set theCommand to "/usr/local/bin/pdftotext -enc UTF-8 some.pdf" & space & searchFile
do shell script theCommand
tell application "Finder"
set companies to get name of folders of folder ("/path/" as POSIX file)
end tell
repeat with company in companies
set theCommand to "grep -c " & quoted form of company & space & quoted form of searchFile
try
do shell script theCommand
set CompanyName to company as string
return CompanyName
on error
end try
end repeat
return false
问题是例如带有变音符号的字符串。当我直接在 CLI 上执行时,“theCommand”的编码方式有所不同。
$ grep -c 'Württemberg' '/tmp/output.txt' --> typed on command line
3
$ grep -c 'Württemberg' '/tmp/output.txt' --> copy & pasted from AppleScript
0
$ grep -c 'rttemberg' '/tmp/output.txt' --> no umlauts, no problems
3
第一行和第二行的“ü”不同; echo 'Württemberg' | openssl base64 显示了这一点。
我在不同的地方尝试了几种编码技巧,基本上我能找到或想到的一切。
有人知道吗?如何检查字符串的编码方式?
提前致谢! 塞巴斯蒂安
【问题讨论】:
-
/tmp/output.txt的内容是什么?它是否包括公司名称列表?您能否编辑您的问题以包括其内容及其示例。通过这样做,它可能会增加您获得合适答案的机会。只有变音符号会导致问题还是还有其他字符? -
感谢您的回答! output.txt 是一个转换后的 pdf 文件 - 我编辑了这篇文章。但是,我认为问题在于
set theCommand to "grep -c '" & company...- 如果我用与公司相同的价值(但硬编码)替换“公司”,它就可以工作。例如。set theCommand to "grep -c '" & "Baden-Württemberg" & "'" & space &工作。 -
ß 也是一个问题。这些是德语特殊字符。
-
请尝试
set theCommand to "grep -c " & quoted form of company & space & quoted form of searchFile。 AppleScript 总是使用quoted form of找到最佳报价。 -
谢谢。我改变了它(并更新了最初的帖子) - 但仍然是同样的问题。
标签: grep applescript