Re: Reversing the lines in a file
Re: Reversing the lines in a file
- Subject: Re: Reversing the lines in a file
- From: Arthur J Knapp <email@hidden>
- Date: Fri, 10 May 2002 11:55:23 -0400
>
From: "Rice, Gary" <email@hidden>
>
Subject: Reversing the lines in a file
>
Date: Thu, 9 May 2002 19:29:18 -0400
>
I have a text file. Each line in the file ends with a <CR>. It is a large
>
file. I want to reverse the order of the file. That is, I want the last line
>
in the file to appear at the begining and the first line in the file to be
>
at the end.
>
>
Can I do this using AppleScript?
I just threw this together, so all the usual warnings apply, ie:
a lot more error-checking is needed, etc.
on ReverseLines(fileSpec)
-- !!! I was too lazy to add all the nessesary error-trapping
-- that is absolutely needed.
-- !!!
set openFile to open for access fileSpec with write permission
set tempPath to path to temporary items folder
set tempPath to (tempPath as string) & "ReverseLines.temp"
--
set tempFile to open for access (file tempPath) with write
permission
set eof tempFile to 0 --> clear from possible previous use
set fileLen to get eof openFile
-- We run into a problem if the last "line" doesn't end with
-- a return, so we proactively add one:
--
set lastChar to read (openFile) from (fileLen)
if (lastChar is not return) then
set fileLen to fileLen + 1
write (return) starting at (fileLen) to (openFile)
end if
write ("") starting at (0) to (openFile) --> file marker to
beginning
set eof tempFile to fileLen --> writes len-amount of garbage to temp
file
set writeMark to fileLen + 1
repeat until writeMark = 1
set oneLine to read (openFile) until (return) --> inclusive of
\r
set lineLen to oneLine's length
set writeMark to writeMark - lineLen
write (oneLine) starting at (writeMark) to (tempFile)
end repeat
-- tempFile is now in the new line-order. We write back to
-- openFile, using a buffering system to protect against
-- large files.
--
set buff to 4096 --> I'm told this is a good buffer size
write ("") to tempFile starting at 0 -- these set the file marker
write ("") to openFile starting at 0 -- to the beginning
repeat (fileLen div buff) times
read (tempFile) until (return)
write (result) to openFile
end repeat
try --> trap eof error
read (tempFile) --> to end
write (result) to openFile
end try
close access tempFile
close access openFile
end ReverseLines
set theFile to choose file
ReverseLines(theFile)
{ Arthur J. Knapp, of <
http://www.STELLARViSIONs.com>
<
mailto:email@hidden>
try
<
http://www.natural-innovations.com/as/>
on error number -128
end try
}
_______________________________________________
applescript-users mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/applescript-users
Do not post admin requests to the list. They will be ignored.