Page 1 of 1 1
Topic Options
#203234 - 2011-10-12 08:51 PM find and replace
booey Offline
Getting the hang of it

Registered: 2005-07-25
Posts: 76
Loc: USA
I have a request to go through several files and essentially do a find and replace. The "found" value will then replace a value that is is the file. In the sample data below, the "Status" value (ABCD, in this example) needs to be taken and replace the "Place" value of XXXX with ABCD. The Status and Place values will vary from file to file as in relates to line number, but they will always be four characters and be listed with the line that starts Place: and Status:. Below is the code I have so far. I've been able to get the place and status values, but I'm not sure how to replace the value in Place with the Status value that I have set in the variables and then save the entire document back in the original format. I've also attached a file that I'm using to test with. Any help is appreciated.

Here's the code I have so far
 Code:
$SO=SETOPTION("Explicit", "ON")
$SO=SETOPTION("NoMacrosInStrings", "ON")
$SO=SETOPTION("NoVarsInStrings", "ON")
BREAK ON

DIM $file
DIM $handle
DIM $read
DIM $line
DIM $c
DIM $M
DIM $sub
DIM $cdetail
DIM $ccode
DIM $mdetail
DIM $mcode


$file = "C:\temp\m\m.txt"


$file = loadfile($file,@CRLF)

For Each $line In $file 

If $line <> 0		
	
If InSTR($line,"Place:") <> 0

	$line ?
	$c = Split($line,":")
	$cdetail = Split($c[1]," ")

		
;$ccode = SubSTR($c[1],14,4)

"p detail: " + $cdetail[14] ?


	Else


EndIf

If InSTR($line,"CODE:") <> 0
	
	$line ?
	$m = Split($line,":")
	$mdetail = Split($m[1]," ")
	
;$mcode = SubSTR($m[1],15,4)
"m detail: " + $mdetail[15] ?


	Else
EndIf


	
EndIf
Next

;Functionction	LoadFile()
;
;Author		Bryce Lindsay Bryce@isorg.net
;
;Action		Loads a file in to a variable or an array.
;
;Syntax		LoadFile("Filename",[Array Delim], [UNI/ANSI file type])
;
;Version	1.1
;
;Date Revised	9:14 AM 8/15/2006
;
;Parameters	Filename
;		name of the file that you want to load.
;
;		Optional Array
;		set this option if you want to return the 
;		information as an array split on the given value
;
;		Unicode/ANSI file type
;		3 = force file open as ANSI
;		2 = forse file open as UNI
;		1 = Opens the file using the system default. (the UDF will use this as default)
;
;Remarks		finaly made this into a UDF and posted it... got tired 
;		of having to hunt it down.
;
;Returns		if the array flag is not set it returns a variable 
;		containing the contents of the file.
;
;		if the array flag is set, it will return an array 
;		of the file split on the value of the given variable
;
;Dependencies	Scripting.FileSystemObject
;
;KiXtart Ver	4.51
; 
;Example(s)	
;		;load the file test.txt into a variable
;		$Data=loadfile('test.txt')
;		? $data 
;
;		;load the file "test.txt" into an array split on @crlf
;		$data = loadfile('test.txt',@crlf)
;		for each $line in $data
;			? $line
;		next
;*/
Function loadfile($file, optional $array, $Uni)
	DIM $fso,$f,$fs
	if $uni $uni = $uni-3 else $uni = -2 endif

	if not $uni $uni = -2 endif
	$fso = CreateObject("Scripting.FileSystemObject")
	$f = $fso.GetFile($file)
	If @ERROR Exit 2 EndIf
	$fs = $f.OpenAsTextStream(1,$uni)
	if not $array
		$loadfile = $fs.Read($f.size)
	else
		$loadfile = Split($fs.Read($f.size),$array)
	endif
	Exit @ERROR 
EndFunction


Attachments
m.txt (144 downloads)
Description:



Top
#203235 - 2011-10-12 09:26 PM Re: find and replace [Re: booey]
Mart Moderator Offline
KiX Supporter
*****

Registered: 2002-03-27
Posts: 4673
Loc: The Netherlands
This works for me.

 Code:
Break on

$file = "D:\m.txt"
$fileold = "D:\m.old"
$filenew = "D:\m.new"

$filecontents = ReadFile($file)


For Each $line in $filecontents
	If Trim($line) <> ""
		If InStr($line, "Status:")
			$line = Split($line, " ")
			$status = $line[UBound($line)]
		EndIf
	EndIf
Next

$rc = Open(1, $filenew, 5)

For Each $line in $filecontents
	If Trim($line) <> ""
		If InStr($line, "Place:")
			? $line
			$line = Split($line, "XXXX")
			$line = Join($line, $status)
			$rc = WriteLine(1, $line + @CRLF)
		Else
			$rc = WriteLine(1, $line + @CRLF)
		EndIf
	EndIf
Next

$rc = Close(1)
Move $file $fileold
Move $filenew $file


;Function	ReadFile()  
;  
;Author		Radimus  
;  
;Contributors	Lonky... This is basically his code that I trimmed down to its  
;		simplest function  
;  
;Action		Reads a file into an array  
;  
;Syntax		$array=ReadFile($file)  
;  
;Version	1.0.1  
;  
;Date           10/21/2003  
;  
;Date Revised   10-22-2003 - dimmed vars 
;  
;Parameters 	file   
;		source filename  
;  
;Remarks	Pair this with WriteFile() to read and write an entire file easily  
;  
;Returns	@error if failed  
;   
;Dependencies 	None  
;  
;KiXtart Ver	4.02  
;   
;Example(s)	$array=ReadFile('c:\file.txt')  
Function ReadFile($file)
	Dim $lf, $f, $_, $t
	$lf = Chr(10)
	$f = FreeFileHandle
	$_ = Open($f, $file)
	If @error Exit @error EndIf
	Do $t = $t + $lf + ReadLine($f) Until @error
	$_ = Close($f)
	$ReadFile = Split(SubStr($t, 2), $lf)
EndFunction
_________________________
Mart

- Chuck Norris once sold ebay to ebay on ebay.

Top
#203236 - 2011-10-12 09:44 PM Re: find and replace [Re: Mart]
ShaneEP Moderator Offline
MM club member
*****

Registered: 2002-11-29
Posts: 2127
Loc: Tulsa, OK
Haha our code is very similar...

But I just stuck with the loadfile(). And wasnt sure if all of the PLACE: values would be XXXX or not, so just stripped the left 20 chrs instead of splitting with it.

 Code:
$inputfile = @ScriptDir+"\242.txt"
$outputfile = @ScriptDir+"\242_temp.txt"

$lines = LoadFile($inputfile,@CRLF)
If @Error = 0
   For Each $line in $lines
      If Left($line,7) = "STATUS:"
         $status = Trim(Split($line,":")[1])
      Endif
   Next
   If Len($status) = 4
      $fh = FreeFileHandle()
      If Open($fh,$outputfile,5) = 0
         For Each $line in $lines
            If Left($line,6) = "Place:"
               $nul = WriteLine($fh,Left($line,20)+$status+@CRLF)
            Else
               $nul = WriteLine($fh,$line+@CRLF)
            Endif
         Next
         $nul = Close($fh)
         Move $inputfile $inputfile+".bkup"
         Move $outputfile $inputfile
      Else
         Exit 1
      Endif
   Else
      Exit 1
   Endif
Else
   Exit 1
Endif

Function loadfile($file, optional $array, $Uni)
	DIM $fso,$f,$fs
	if $uni $uni = $uni-3 else $uni = -2 endif
	if not $uni $uni = -2 endif
	$fso = CreateObject("Scripting.FileSystemObject")
	$f = $fso.GetFile($file)
	If @ERROR Exit 2 EndIf
	$fs = $f.OpenAsTextStream(1,$uni)
	if not $array
		$loadfile = $fs.Read($f.size)
	else
		$loadfile = Split($fs.Read($f.size),$array)
	endif
	Exit @ERROR 
EndFunction

Top
#203237 - 2011-10-12 09:49 PM Re: find and replace [Re: Mart]
booey Offline
Getting the hang of it

Registered: 2005-07-25
Posts: 76
Loc: USA
Thanks for the quick reply. This does essentially what I need, however, I didn't make clear that the value in the Place line will not always be XXXX. I was just using that as a placeholder. It can be any four characters. With that being said, what's the best way to get those characters from the string?

Also, how do I keep the formatting the same as it was in the original file. That is, keep empty lines as is instead of removing them?

Thanks.

Top
#203239 - 2011-10-12 10:04 PM Re: find and replace [Re: booey]
ShaneEP Moderator Offline
MM club member
*****

Registered: 2002-11-29
Posts: 2127
Loc: Tulsa, OK
I thought that may be the case...Give this a shot (just change the file paths)...

 Code:
$inputfile = @ScriptDir+"\242.txt"
$outputfile = @ScriptDir+"\242_temp.txt"

$lines = LoadFile($inputfile,@CRLF)
If @Error = 0
   For Each $line in $lines
      If Left($line,7) = "STATUS:"
         $status = Trim(Split($line,":")[1])
      Endif
   Next
   If Len($status) = 4
      $fh = FreeFileHandle()
      If Open($fh,$outputfile,5) = 0
         For Each $line in $lines
            If Left($line,6) = "Place:"
               $nul = WriteLine($fh,Left($line,20)+$status+Right($line,-24)+@CRLF)
            Else
               $nul = WriteLine($fh,$line+@CRLF)
            Endif
         Next
         $nul = Close($fh)
         Move $inputfile $inputfile+".bkup"
         Move $outputfile $inputfile
      Else
         Exit 1
      Endif
   Else
      Exit 1
   Endif
Else
   Exit 1
Endif

Function loadfile($file, optional $array, $Uni)
	DIM $fso,$f,$fs
	if $uni $uni = $uni-3 else $uni = -2 endif
	if not $uni $uni = -2 endif
	$fso = CreateObject("Scripting.FileSystemObject")
	$f = $fso.GetFile($file)
	If @ERROR Exit 2 EndIf
	$fs = $f.OpenAsTextStream(1,$uni)
	if not $array
		$loadfile = $fs.Read($f.size)
	else
		$loadfile = Split($fs.Read($f.size),$array)
	endif
	Exit @ERROR 
EndFunction

Top
#203240 - 2011-10-12 10:07 PM Re: find and replace [Re: ShaneEP]
ShaneEP Moderator Offline
MM club member
*****

Registered: 2002-11-29
Posts: 2127
Loc: Tulsa, OK
Or you can use Mart's by just changing this...

 Code:
			? $line
			$line = Split($line, "XXXX")
			$line = Join($line, $status)
			$rc = WriteLine(1, $line + @CRLF)

To something like this...
 Code:
			? $line
			$line = Left($line, 20)+$status+Right($line, 24)
			$rc = WriteLine(1, $line + @CRLF)

Top
#203241 - 2011-10-12 10:17 PM Re: find and replace [Re: ShaneEP]
booey Offline
Getting the hang of it

Registered: 2005-07-25
Posts: 76
Loc: USA
Excellent! It's working. Thanks to both of you for the help.
Top
Page 1 of 1 1


Moderator:  Jochen, Allen, Radimus, Glenn Barnas, ShaneEP, Ruud van Velsen, Arend_, Mart 
Hop to:
Shout Box

Who's Online
0 registered and 525 anonymous users online.
Newest Members
batdk82, StuTheCoder, M_Moore, BeeEm, min_seow
17885 Registered Users

Generated in 0.033 seconds in which 0.014 seconds were spent on a total of 14 queries. Zlib compression enabled.

Search the board with:
superb Board Search
or try with google:
Google
Web kixtart.org