Page 1 of 1

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

Posted: 21 Dec 2018, 02:41
by afe
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

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

Posted: 21 Dec 2018, 05:05
by hymal7

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

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

Posted: 21 Dec 2018, 05:15
by garry
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

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

Posted: 21 Dec 2018, 11:27
by afe
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.