读取和写入特定的文本文件行

时间:2013-09-07 21:38:37

标签: text applescript

在AppleScript中,如何读/写.rtf文件的特定行。到目前为止,我可以使用

添加/替换文件到文件
tell application "TextEdit"
        set text of document 1 to "test"
end tell

但我怎样才能选择一条线。另外我怎样才能将var设置为第4行的文本?

2 个答案:

答案 0 :(得分:3)

您可以获得第四段(由换行符,回车符或回车符+换行符分隔的项目),如下所示:

tell application "TextEdit"
    paragraph 4 of document 1
end tell

在TextEdit中,您实际上可以更改段落:

tell application "TextEdit"
    set paragraph 4 of document 1 to "zz" & linefeed
end tell

通常尝试更改段落会导致错误:

set paragraph 1 of "aa" & linefeed & "bb" to "zz"
-- error "Can’t set paragraph 1 of \"aa
-- bb\" to \"zz\"."

如果其他人搜索如何将文本附加到纯文本文件,则可以将starting at eof说明符与write命令一起使用:

set fd to open for access "/tmp/a" with write permission
write "aa" & linefeed to fd as «class utf8» starting at eof
close access fd

这将第四行替换为zz

set input to read "/tmp/a" as «class utf8»
set text item delimiters to linefeed
set ti to text items of input
set item 4 of ti to "zz"
set fd to open for access "/tmp/a" with write permission
set eof fd to 0
write (ti as text) to fd as «class utf8»
close access fd

答案 1 :(得分:1)

当然你可以做到。

tell application "TextEdit"
    set abc to text of document 1
end tell
set text item delimiters to "
"
set abc to item 4 of text items of abc

首先我们得到文档1的文本。(你不能命名一个变量文本。这是一个保留字。)

tell application "TextEdit"
    set abc to text of document 1
end tell

然后我们将文本项分隔符设置为行返回。 (仅当您按下“”)中的返回按钮时才有效。

set text item delimiters to "
"

最后一点是,我们采取第4个文本项目。 (这是第4行,因为我们设置了分界线换行符)

set abc to item 4 of text items of abc

(此脚本仅在用户按下文本编辑中的输入以开始新行时才有效)