I need some help to get me started with writing a script which searches for a string and replaces only the first occurrence of the text found.
The document (as received from my customer) contains an index, like this (very common):
I want to find the first occurence of A and B and C and so on and change that to the following result:
I have looked at the example scripts of InDesign CS3, like 'ChangeText':
//Search the document for the string "copy" and change it to "text".
app.findTextPreferences.findWhat = "copy";
app.changeTextPreferences.changeTo = "text";
But that script changes all text found and I can't figure out how to change the first occurrence only.
Can someone give a clue how to solve this?
Thanks and regards,
If your index doesn't contain any formatting and if each topic name starts with an upper-case letter, you can use this grep query:
Find what: ^(\u).+\r(\1.+\r)+
Change to: $1\r$0
Here's a breakdown:
^ from beginning of paragraph
(\u) upper-case letter, create referent (the referent is created by the parentheses)
.+ any characters. . .
\r . . .up to and including the paragraph mark
(up to here the code says 'match a paragraph that starts with a uc letter)
( begin grouping
\1 reference to the first variable, that's the uc letter
.+\r again to the end of the paragraph, including the paragraph mark
) close the group
+ repeat at least once
Do this in the interface and you'll see that each time you press Find, a block of paragraphs is selected that start with the same letter.
The Change to expression says 'replace the block with the captial we matched followed by a retrurn and the whole group'.
As I said, this works only on unformatted text, and non-letters (quotation marks, brackets, etc.) spoil things. To cope with these situations you need some script.