1

In AppleScript how can you read/write to a specific line of a .rtf file. so far I can add/replace text to the file with

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

But how can I pick a certain line. also how can I do something like set a var to the text of line 4?

4

2 回答 2

3

You can get the fourth paragraph (item separated by a linefeed, a carriage return, or carriage return + linefeed) like this:

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

In TextEdit you can actually change the paragraphs:

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

Normally trying to change a paragraph results in an error though:

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

If others search for how to append text to a plain text file, you can use the starting at eof specifier with the write command:

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

This replaces the fourth line with 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
于 2013-09-08T22:32:46.807 回答
1

Of course you can do that.

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

First we are getting the text of document 1. (You can't name a variable text. That's a reserved word.)

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

Then we set the text item delimiters to line return. (It only works if you press the return button within the "")

set text item delimiters to "
"

The last thing is, that we take the 4th text item. (That's the 4th line, because we have set to delimiters line break)

set abc to item 4 of text items of abc

(This script works only if the user press enter in Text Edit to begin an new line)

于 2013-09-08T13:18:07.183 回答