What is best way to read 5 last rows of plain text file to variable?
And then what is best way to delete 3rd last row in that text?
What is best way to read 5 last rows of plain text file to variable?
And then what is best way to delete 3rd last row in that text?
Hello,
use something like this
set p2File to quoted form of "/path/to/your/file.txt"
set lastRows to 5
set omitLine to 3
set omitRange to "3,10"
-- last rows
set var1 to do shell script "tail -n" & space & lastRows & space & p2File
-- omit 1 line
set var2 to do shell script "sed " & quoted form of ((omitLine & "d") as string) & space & p2File
-- omit line range
set var3 to do shell script "sed " & quoted form of ((omitRange & "d") as string) & space & p2File
set p2File to quoted form of "/path/to/your/file.txt"
set lastRows to 5
set omitLine to 3
set var4 to do shell script "/usr/bin/tail -n" & space & lastRows & space & p2File & " | " & "/usr/bin/sed " & quoted form of ((omitLine & "d") as string)
try this
set {TID, text item delimiters} to {text item delimiters, return}
tell paragraphs of (read file ((path to desktop as text) & "test.txt")) to set myText to items -5 thru -4 & items -2 thru -1
set myText to myText as text
set text item delimiters to TID
myText
This out-Kais Stefan’s offering and preserves the original line endings:
tell text from paragraph -5 to -1 of (read file ((path to desktop as text) & "test.txt") as text) to set myText to text 1 thru ((count (text 1 thru paragraph 3)) - (count paragraph 3)) & text from paragraph 4 to -1
-- Breakdown:
(* set fileText to (read file ((path to desktop as text) & "test.txt") as text)
set last5paras to text from paragraph -5 to -1 of fileText
set cutPoint to (count text 1 thru paragraph 3 of last5paras) - (count paragraph 3 of last5paras)
set myText to (text 1 thru cutPoint of last5paras) & (text from paragraph 4 to -1 of last5paras) *)
Thanks.
I tried this but it don’t save new text back to same text file. What i’m doing wrong?
none of the scripts does that because you asked only for “read . plain text file to variable . delete”.
You need an extra write command ( > or AppleScript’s write)