How to replace string in a line in a file without deleting file? Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
afe
Posts: 615
Joined: 06 Dec 2018, 04:36

How to replace string in a line in a file without deleting file?

21 Dec 2018, 02:41

Hello,

I want to replace a string in a line in a text file. How do I do this?

For example, replace 01 in test.txt with 03.

Thanks.

test.txt

Code: Select all

a = 01
b = 02
To

Code: Select all

a = 03
b = 02
hymal7
Posts: 66
Joined: 14 Sep 2016, 05:37

Re: How to replace string in a line in a file without deleting file?  Topic is solved

21 Dec 2018, 05:05

Code: Select all

fileread, contents,  %A_Desktop%/testing.txt	;reads the notepad
loop, parse, contents, `n
{
	if instr(a_loopfield,"a")	;if line contains "a"
	{
		if instr(a_loopfield,"01")	;if line contains "01"
		{
			stringreplace, contents, contents, 01, 03, All		;replace "01" with "03"
		}
	}
}

;replace the notepad with changes
filedelete, %A_Desktop%/testing.txt
fileappend, %contents%, %A_Desktop%/testing.txt

;#######################################################################
exitapp
esc::ExitApp
garry
Posts: 3787
Joined: 22 Dec 2013, 12:50

Re: How to replace string in a line in a file without deleting file?

21 Dec 2018, 05:15

see function
https://www.autohotkey.com/boards/viewt ... unction+TF
TF v3.7 - AutoHotkey library for Text files & Variables (strings)
TF_ReplaceLine

also ( deletes file )

Code: Select all

cm= a = 01                    ; - orig
en= a = 03                    ; - new
fx=%a_scriptdir%\test.txt
ifnotexist,%fx%
{
e=
(
a = 01
b = 02
)
fileappend,%e%,%fx%
}
e=
;-----------------------------
FileRead,a,%fx% 
FileDelete, %fx%
StringReplace,a,a, %cm%,%en%
FileAppend, %a%, %fx%,UTF-8
a=
return
afe
Posts: 615
Joined: 06 Dec 2018, 04:36

Re: How to replace string in a line in a file without deleting file?

21 Dec 2018, 11:27

hymal7 wrote:
21 Dec 2018, 05:05

Code: Select all

fileread, contents,  %A_Desktop%/testing.txt	;reads the notepad
loop, parse, contents, `n
{
	if instr(a_loopfield,"a")	;if line contains "a"
	{
		if instr(a_loopfield,"01")	;if line contains "01"
		{
			stringreplace, contents, contents, 01, 03, All		;replace "01" with "03"
		}
	}
}

;replace the notepad with changes
filedelete, %A_Desktop%/testing.txt
fileappend, %contents%, %A_Desktop%/testing.txt

;#######################################################################
exitapp
esc::ExitApp
Great, clear and concise, thank you.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Bing [Bot], CoffeeChaton, Rohwedder and 143 guests