提问人:jeff 提问时间:3/26/2023 更新时间:3/27/2023 访问量:81
使用 sed 问题运行 AppleScript 正则表达式
Running AppleScript Regex using sed problems
问:
我正在尝试在AppleScript下使用sed来执行正则表达式命令。目标是运行一系列正则表达式命令来清理文本。我尝试使用 TextEdit 应用程序作为要传递给正则表达式命令的数据源。在我注释掉查找孤立的“:”和“;”的两个表达式之前,它不会运行。
该脚本运行并且没有错误,但它也不会影响正则表达式通信应该处理的任何文本问题。我能做些什么来让它运行?我从没想过一些简单的文本 mungung 在 AppleScript 中会如此困难。
tell application "TextEdit" to activate
set the clipboard to ""
tell application "System Events" to keystroke "c" using command down -- copy
delay 1 -- test different values
set selectedText to the clipboard as Unicode text
if selectedText is "" then
display dialog "Text selection not found"
return
end if
-- Replace ". " with ". "
set selectedText to do shell script "echo " & quoted form of selectedText & " | sed 's/\\. /\\. /g'"
-- Replace " " with " "
set selectedText to do shell script "echo " & quoted form of selectedText & " | sed 's/ / /g'"
-- Replace " " with " "
set selectedText to do shell script "echo " & quoted form of selectedText & " | sed 's/ / /g'"
-- Replace ", " with ", "
set selectedText to do shell script "echo " & quoted form of selectedText & " | sed 's/, /, /g'"
-- Replace ":" without a space after with ": "
--set selectedText to do shell script "echo " & quoted form of selectedText & " | sed 's/:\([^[:space:]]\)/: \\1/g'"
-- Replace ";" without a space after with "; "
--set selectedText to do shell script "echo " & quoted form of selectedText & " | sed 's/;\([^[:space:]]\)/; \\1/g'"
-- Replace curly quotes with straight quotes
set selectedText to do shell script "echo " & quoted form of selectedText & " | sed 's/[“”‘’]/\"/g'"
-- Replace multiple carriage returns with one carriage return
set selectedText to do shell script "echo " & quoted form of selectedText & " | awk 'BEGIN{RS=\"\";FS=\"\\n\"}{for(i=1;i<=NF;i++)if($i)printf(\"%s%s\",$i,i==NF?\"\":\"\\n\")}'"
-- Replace repeated words with one occurrence of the word
set selectedText to do shell script "echo " & quoted form of selectedText & " | sed -E 's/(\\b\\w+\\b)(\\s+\\1)+/\\1/g'"
-- Capitalize the first letter after a period and lowercase the rest
set selectedText to do shell script "echo " & quoted form of selectedText & " | sed -E 's/\\b([a-z])|\\.\\s+(.)/\\U\\1\\L\\2/g'"
set the clipboard to selectedText
delay 1
tell application "System Events" to keystroke "v" using command down -- paste
我已经注释掉了两个阻止脚本运行的正则表达式命令,并且脚本将耗尽不返回任何内容。
答:
0赞
markalex
3/27/2023
#1
你错过了反斜杠来逃避你的反斜杠。
" | sed 's/;\([^[:space:]]\)/; \\1/g'"
------------^-------------^-----------
here and here
请改用以下方法:
" | sed 's/;\\([^[:space:]]\\)/; \\1/g'"
解释:我不确定applescript在这种情况下的行为,但我猜你的命令变成了这样:
echo something | sed 's/;([^[:space:]])/; \1/g'
由于您使用 BRE(顺便说一句,不一致),sed 会在非空格字符周围寻找文字括号。
评论
0赞
jeff
3/28/2023
感谢您的见解。今晚我会带着新的见解重新深入研究它。
评论