Remove line from text file

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Wigry3
Posts: 8
Joined: 07 Jan 2022, 05:24

Remove line from text file

Post by Wigry3 » 26 Jan 2022, 10:24

Hi, How can I remove the line that contains "apple" from the text file? Please help me

BoBo
Posts: 6564
Joined: 13 May 2014, 17:15

Re: Remove line from text file

Post by BoBo » 26 Jan 2022, 10:28

Code: Select all

FileRead		; get content from file
StrReplace()	; replace whatever from content with nothing
FileAppend		; create new file with the edited content
PseudoCode. Click commands for further details. HTH

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

Re: Remove line from text file

Post by boiler » 26 Jan 2022, 10:34

You would have to check each line and not include lines that contain "apple" in the output that replaces the original file.

Code: Select all

FileRead, Text, mytextfile.txt
loop, Parse, Text, `n, `r
	if !InStr(A_LoopField, "apple")
		OutText .= A_LoopField "`n"
OutText := SubStr(OutText, 1, -1) ; remove last `n
FileMove, mytextfile.txt, mytextfile.bak, 1 ; create backup file
FileDelete, mytextfile.txt ; delete original file (or else it would add on to old contents)
FileAppend, % OutText, mytextfile.txt ; write new file

Btw, StrReplace() would be good for removing only the word "apple" itself, but not the whole line that contains "apple". You could do something like that with RegExReplace().
Last edited by boiler on 26 Jan 2022, 10:41, edited 1 time in total.

BoBo
Posts: 6564
Joined: 13 May 2014, 17:15

Re: Remove line from text file

Post by BoBo » 26 Jan 2022, 10:40

Btw, StrReplace() would be good for removing only the word "apple" itself
Oops, correct! :thumbup:

Post Reply

Return to “Ask for Help (v1)”