This applescript allows me to extract the text I'm interested in from a .gcode file but actually creates a copy of the file before modifying the original file. I would like to save the file without adding a ".copy" extension but rather renaming the copy with "original_" and keeping the .gcode extension.
use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
on run
-- Handle the case where the script is launched without any dropped files
set sourceFile to choose file of type {"gcode"} with prompt "Select the .gcode file(s)"
processFile(sourceFile)
end run
on processFile(sourceFile)
-- Make a copy of the file before making changes
set originalPath to POSIX path of (sourceFile as text)
set copyPath to originalPath & ".copy"
do shell script "cp " & quoted form of originalPath & " " & quoted form of copyPath
set fileURL to sourceFile as «class furl»
set fileDescriptor to open for access fileURL with write permission
set theText to read fileDescriptor
set {saveTID, text item delimiters} to {text item delimiters, {"; EXECUTABLE_BLOCK_START"}}
try
set {startBlock, remainder} to text items of theText
set text item delimiters to {"; EXECUTABLE_BLOCK_END" & linefeed & linefeed}
set endBlock to text item 2 of remainder
set text item delimiters to saveTID
set eof of fileDescriptor to 0
write (startBlock & endBlock) to fileDescriptor
close access fileDescriptor
on error e number n
if n = -1728 then
close access fileDescriptor
else
close access fileURL
end if
set text item delimiters to saveTID
end try
end processFile
In your example you can just add the prefix to the name, but the Finder or System Events can provide various pieces of a file path that can be used to reassemble the name or path however you want, for example:
set sourceFile to (choose file) -- example
set originalPath to POSIX path of (sourceFile as text)
set {directory, justTheName, extension} to (getNamePieces from originalPath)
set copyPath to directory & "original_" & justTheName & extension -- or whatever
to getNamePieces from filePath
tell application "System Events" to tell disk item (filePath as text)
set directory to (POSIX path of container) & "/"
set {theName, extension} to {name, name extension}
end tell
if extension is not "" then
set theName to text 1 thru -((count extension) + 2) of theName
set extension to "." & extension
end if
return {directory, theName, extension}
end getNamePieces