Overwrite line 1 in a textfile

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
WantToKnow
Posts: 64
Joined: 28 Mar 2020, 08:46

Overwrite line 1 in a textfile

Post by WantToKnow » 06 Oct 2022, 05:11

I'd like to overwrite given lines in a textfile.

Code: Select all

; Write a testfile 
F1::
FileDelete Test.txt
arr1:=[]
Loop 20
{
  Random, out1 , 66, 83
  str1 := ; ! zurücksetzen
  Loop 7
   str1 .= Chr(A_index + out1)   ; ! A_Index innen
  arr1[A_index] := A_Index "." A_Space str1 ; A_Index aussen
}
Loop 20
FileAppend % arr1[A_index] "`n", Test.txt
return

F2:: ; Overwrite  a certain line
file := FileOpen("Test.txt","rw`r") ; open
Loop
{
 Line := file.ReadLine()
 If (A_Index = 1)  ; Overwrite line 2 etc.
 {
 file.WriteLine("Overwrite in this case line 2")
 file.close()
 break
 }
}
Run Test.txt,, max
return
Since I always have to subtract one from A_index to delete
the corresponding line and there is no A_index 0, how do I delete line 1 in my text file?

A big thank in advance for your help.

User avatar
boiler
Posts: 17047
Joined: 21 Dec 2014, 02:44

Re: Overwrite line 1 in a textfile

Post by boiler » 06 Oct 2022, 05:17

Move the file.ReadLine() to after the file.WriteLine(), so put it as the last line of the loop, not the first line. Then you wouldn’t subtract 1 from A_Index because the file pointer would be at the beginning of the line number A_Index, not at the end of it.

Post Reply

Return to “Ask for Help (v1)”