Jump to content

StringReplace from string with line break


Recommended Posts

Im trying to edit a file, I want to find a string which has a line break in it, and replace it with a string that has multiple line breaks in it.

editfile.txt looks like this:

dog
cat
mouse
chicken

my au3 script looks like this but is not working, i suspect because of how I am trying to do the line breaks?

Func EditFile($CurrentFile)

$szFile = "$CurrentFile"

$szText = FileRead($szFile,FileGetSize($szFile))

$szText = StringReplace($szText, "Cat" & @CRLF & "Dog", "Hippo" & @CRLF "Lion" & @CRLF & "Tiger")

FileDelete($szFile)

FileWrite($szFile,$szText)

EndFunc ;--EditFile--

But once ran the file should look like this:

Hippo
Lion
Tiger
cat
mouse
chicken

I cannot replace by line number as the animals are not in the same line in each copy of the file i want to run against.

 

Can anyone help?

Link to comment
Share on other sites

Use FileOpen with mode 2 before writing:

$szFile = "editfile.txt"

$szText = FileRead($szFile)
;$szText = StringReplace($szText, "dog" & @CRLF & "cat", "Hippo" & @CRLF &"Lion" & @CRLF & $szText = StringReplace($szText, "dog", "Hippo" & @CRLF &"Lion" & @CRLF & "Tiger")
$hFile=FileOpen($szFile,2)
$hFile=FileOpen($szFile,2)
FileWrite($hFile,$szText)
FileClose($hFile)

Btw.:  your script didn't run:

>Running AU3Check (3.3.14.2)  from:C:\Program Files\AutoIt3  input:C:\Users\Bert\AutoIt3.My\Temp\editfile.au3
"C:\Users\Bert\AutoIt3.My\Temp\editfile.au3"(7,79) : error: syntax error
$szText = StringReplace($szText, "Cat" & @CRLF & "Dog", "Hippo" & @CRLF "Lion"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\Users\Bert\AutoIt3.My\Temp\editfile.au3 - 1 error(s), 0 warning(s)

and as the animals in textfile are in a other order than you have used in script, it wouldn't run also when syntax is corrected.

Edited by AutoBert
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...