Saturday, November 18, 2017

#1 2011-06-29 04:24:50 am

bensonang
Member
Registered: 2008-06-03
Posts: 50

Need Help! string manipulation?

I'm currently making a script to copy the contents of a file, append a new string at the end of the file, and write a new file. My problem now is that in the existing file, there is a bracket which is supposed to be at the end of the file. What should I do to append the new string to the file just before the bracket? I'm really stuck on this problem and I hope someone could help.

illustration:

this is how the source file looks like:

main {
   var a
   var b
   var c
}

this is how the new file should look like after appending NEW STRING:

main {
   var a
   var b
   var c
   NEW STRING
}

this is how the ACTUAL OUTPUT file looks like after appending NEW STRING:

main {
   var a
   var b
   var c
}
   NEW STRING
}

notice the extra "}"

i'm using simple file handling (see code below)

Applescript:


   set theFile to (open for access (POSIX file unixPath))
   set theText to (read theFile for (get eof theFile))
   close access theFile

set theFileContents to theText & "NEW STRING" & return & "}"
   set theFile to (open for access (POSIX file theFile) with write permission)
   write theFileContents to theFile as string
   close access theFile


Filed under: file handling

Offline

 

#2 2011-06-29 10:00:30 am

DJ Bazzie Wazzie
Member
From:: the Netherlands
Registered: 2004-10-20
Posts: 2724
Website

Re: Need Help! string manipulation?

The most simplest answer is

Applescript:

set sourceCode to "main {
var a
var b
var c
}"

set codeToAdd to "var x"

set AppleScript's text item delimiters to string id 10 --or string id 13
set newCode to text items 1 thru -2 of sourceCode & codeToAdd & text item -1 of sourceCode as string
set AppleScript's text item delimiters to ""

return newCode

But I don't like this approach. Probably it's something from a programming/scriptinglanguage and I prefer to parse the source code just like a compiler/interpreter would do. In this case the accolades means that it is a list of commands separated with a return

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)