Nick
Nick

Reputation: 1056

Remove text between two strings Applescript

I have successfully grabbed the text I want to delete but then when I try and delete the chunk of text I have specified it throws an error

set startText to "<target object=\"3097595957\" channel=\"./2/100\" name=\"\"/>"
set endText to "<target object=\"3097805072\" channel=\"./2/100\" name=\"\"/>"

set theFile to POSIX path of newNameFull
set theContent to read theFile as «class utf8»

set AppleScript's text item delimiters to startText
set bigChunk to text items of theContent
set AppleScript's text item delimiters to endText

        repeat with subText in bigChunk

            if subText contains endText then

                display dialog subText

                delete subText

            end if

        end repeat 

When I display the subtext it is the correct text that I want to be removed. But then when i try to delete it i get this error:

Finder got an error: Handler can’t handle objects of this class. (-10010)

I have tried researching this error and I am thoroughly confused. If anyone has any advice or can help then that would be greatly appreciate. Thanks in advance.

Upvotes: 0

Views: 415

Answers (1)

vadian
vadian

Reputation: 285069

Do the following:

  • Get the text before startText (text1)
  • Get the text after endText (text2)
  • Concatenate text1 & startText & endText & text2

set startText to "<target object=\"3097595957\" channel=\"./2/100\" name=\"\"/>"
set endText to "<target object=\"3097805072\" channel=\"./2/100\" name=\"\"/>"

set theFile to POSIX path of newNameFull
set theContent to read theFile as «class utf8»

set ASTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to startText
set text1 to text item 1 of theContent
set AppleScript's text item delimiters to endText
set text2 to text item 2 of theContent
set AppleScript's text item delimiters to ASTID
set trimmedText to text1 & startText & endText & text2

The result is in the variable trimmedText. You might save the text back to disk.

Upvotes: 1

Related Questions