将Grep Applescript自动化为Word文档

时间:2016-08-31 11:25:09

标签: ms-word grep applescript automator

我正在使用Mac,而我正在为一家公司准备帐户。我在Microsoft Word中制作的每个工资单都有一个凭证编号。因为错过了一笔交易所有凭证号码都是错误的,所以现在有数百个错误的工资单。我想创建一个脚本,可以找到以下GREP(找到段落的开头,文本:Vch,任何字符直到\ r \ n):

^Vch.+\r

并将其替换为空(从而删除整个句子)。

我正在考虑使用Applescript,因为它可以打开文档,执行GREP查找(棘手的部分),保存文档并将其保存为pdf(所有这些都需要)。

但显然我的知识让我失望。字典中的命令如create range,execute find,都会带来错误。

有人在Applescript中有经验可以帮助我设计脚本吗?有什么建议?它应该是这样的:

Tell application "Microsoft Word"
  tell active document
  set myRange to create range start 0 end 0
    tell myRange
      execute find find "^Vch.+\r" replace with ""
    end tell
  end tell
end tell

非常感谢!

1 个答案:

答案 0 :(得分:1)

There are no special characters to indicate the beginning of a line.

To search at beginning of the paragraph, the script must use return & "some text"

You can use "^p" as paragraph mark, but it doesn't work when you set the match wildcards property to true

To match an entire paragraph, the script must use return & "some text" & return, and the script must use replace with return to delete one paragraph mark instead of two.

Because the first paragraph does not begin with a paragraph mark, the script must use two execute find commands.

The wildcard is *


tell application "Microsoft Word" -- (tested on version 15.25,  Microsoft Office 2016)

    -- check the first  paragraph
    select (characters of paragraph 1 of active document)
    execute find (find object of selection) find text ("Vch*" & return) replace with "" replace replace one wrap find find stop with match wildcards and match case without match forward and find format

    --to search forward toward the end of the document.
    execute find (find object of selection) find text (return & "Vch*" & return) replace with return replace replace all wrap find find continue with match wildcards, match case and match forward without find format

    save active document

    -- export to PDF in the same directory as the active document
    set pdfPath to path of active document & ":" & (get name of active window) & ".pdf"
    set pdfPath to my createFile(pdfPath) -- create an empty file if not exists, the handler return a path of type alias (to avoid grant access issue)
    save as active document file name pdfPath file format format PDF
end tell

on createFile(f)
    do shell script "touch " & quoted form of POSIX path of f
    return f as alias
end createFile