Page 1 of 1 1
Topic Options
#209323 - 2014-07-31 03:18 PM Search Text in file and Replace
Valentim Offline
Fresh Scripter

Registered: 2010-01-04
Posts: 46
Loc: Brazil, PE, Recife
Instead of using UDF -> "insertline ()" which replaces the whole line, it can search for a specific word within a text file and replace it with another word or return the line number where the text was found?

I need this information to be able to read 30 files, where the text I want replace is in different lines.

Example:

File1: Text -> "SourcePath" in line 5
File2: Text -> "SourcePath" in line 8
File3: Text -> "SourcePath" in line 6
File4: Text -> "SourcePath" in line 3

These files are configuration of a server
_________________________

Top
#209325 - 2014-07-31 06:44 PM Re: Search Text in file and Replace [Re: Valentim]
Glenn Barnas Administrator Offline
KiX Supporter
*****

Registered: 2003-01-28
Posts: 4403
Loc: New Jersey
Here's the general idea:
 Code:
; Define the Old and New words
$Old = Oldword
$New = Newword

; Enumerate the list of files.. either from a fixed list (shown below) or using the DIR command
$aFiles = 'File1', 'File2'
For Each $File in in $aFiles
  ; Load the file into an array. Use the FileIO() UDF
  $aData = FileIO($File, 'R')

  ; enumerate the file and replace any occurrence of the word
  For $Ptr = 0 to UBound($aData)
    $aData[$Ptr] = Join(Split($aData[$Ptr], $Old), $New)
  Next
Next
; Write the updated file back
$aData = FileIO($File, 'W', $aData)
Given, this is an EXAMPLE of how it could be done - you'll need to flesh it out with some error checking and possibly other logic to insure that only specific instances are replaced, but this shows how to enumerate a list of files, and then enumerate the contents of each file.

Glenn

PS - the latest FileIO UDF can be downloaded from my web site.
_________________________
Actually I am a Rocket Scientist! \:D

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
1 registered (Henriques) and 2516 anonymous users online.
Newest Members
fgarcia, Viginette, ManuvdWielNL, Sir_Barrington, batdk82
17889 Registered Users

Generated in 0.202 seconds in which 0.142 seconds were spent on a total of 13 queries. Zlib compression enabled.

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