Jump to content

Search Replace just in certain lines


 Share

Recommended Posts

I have been doing a search and replace like this

$szFile = "attrib.dat"
$szText = FileRead($szFile,FileGetSize($szFile))
$szText = StringReplace($szText, "0f3436285,0 Ken,1 Griffey Jr.,2 3,3 1,4 1,5 7,6 8,7 27,8 120,9 33,10 9,11 0", "0f3436285,0 Ken,1 Griffey Jr.,2 3,3 1,4 1,5 7,6 8,7 27,8 120,9 33,10 9,11 1")
$szText = StringReplace($szText, "015ff7627,0 Johan,1 Santana,2 57,3 1,4 1,5 0,6 10,7 24,8 105,9 28,10 516,11 0" , "015ff7627,0 Johan,1 Santana,2 57,3 1,4 1,5 0,6 10,7 24,8 105,9 28,10 516,11 1")
FileDelete($szFile)
FileWrite($szFile,$szText)

But is there a way to Search and replace just in lines that start with a certain string

example

0fff5024a,0 Erick,1 Abreu,2 23,3 0,4 0,5 0,6 10,7 25,8 75,9 27,10 908,11 0,12 3
00567dacc,0 Etanislao,1 Abreu,2 12,3 0,4 0,5 5,6 3,7 23,8 60,9 27,10 911,11 0,12 5
0fff504e8,0 Johany,1 Abreu,2 47,3 2,4 0,5 5,6 12,7 24,8 65,9 26,10 907,11 0,12 3
0fff4ffd8,0 Winston,1 Abreu,2 22,3 0,4 0,5 10,6 10,7 28,8 87,9 26,10 910,11 0,12 3
0fff501c1,0 Jared,1 Abruzzo,2 29,3 2,4 0,5 1,6 2,7 27,8 115,9 29,10 903,11 0,12 5
05e56a183,0 Jeremy,1 Accardo,2 59,3 0,4 0,5 10,6 0,7 26,8 90,9 28,10 902,11 0,12 3
0f0baf259,0 Jose,1 Acevedo,2 30,3 0,4 0,5 10,6 0,7 24,8 120,9 31,10 909,11 0,12 5
0b06e23e8,0 Jonathan,1 Aceves,2 63,3 0,4 0,5 1,6 2,7 26,8 120,9 30,10 902,11 0,12 9
0fff50320,0 Kelyn,1 Acosta,2 29,3 0,4 0,5 10,6 0,7 25,8 70,9 26,10 909,11 0,12 3

If the line starts with "0fff501c1" then in that line only change "11 0" to 11 1"

The reason I need something like this is because the data between "0fff501c1" and "11 0" changes all the time

Is it be possible to determine a line # that contains a certain string and then use StringReplace on the given line #

Thanks

Link to comment
Share on other sites

Have a look at the User Defined Function in the Helpfile for a function called _FileReadToArray().

The example on the page shows you how to use a For...Next loop. Each element of the array will contain a line of text which you can check with StringLeft() to find your line to use StringReplace on.

:whistle:

Link to comment
Share on other sites

  • Moderators

StringRegExp() in beta would be a faster solution for this I think:

;String could be a FileRead() so the string would be the whole file to search for it
$String = '0fff501c1,0 Jared,1 Abruzzo,2 29,3 2,4 0,5 1,6 2,7 27,8 115,9 29,10 903,11 0,12 5'
$aString = _SRE_Between($String, "0fff501c1,0 ", ",11 0,12 5")
If IsArray($aString) Then
    For $i = 0 To UBound($aString) - 1
        ;Here's where you would replace it with whatever
        MsgBox(64, 'The String Between', $aString[$i])
    Next
EndIf

Func _SRE_Between($s_String, $s_Start, $s_End)
    $a_Array = StringRegExp($s_String, '(?:' & $s_Start & ')(.*?)(?:' & $s_End & ')', 3)
    If IsArray($a_Array) Then Return $a_Array
EndFunc
If the 11 0, 12 5 is a constant on the end always...

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

StringRegExp() in beta would be a faster solution for this I think:
;String could be a FileRead() so the string would be the whole file to search for it
$String = '0fff501c1,0 Jared,1 Abruzzo,2 29,3 2,4 0,5 1,6 2,7 27,8 115,9 29,10 903,11 0,12 5'
$aString = _SRE_Between($String, "0fff501c1,0 ", ",11 0,12 5")
If IsArray($aString) Then
    For $i = 0 To UBound($aString) - 1
        ;Here's where you would replace it with whatever
        MsgBox(64, 'The String Between', $aString[$i])
    Next
EndIf

Func _SRE_Between($s_String, $s_Start, $s_End)
    $a_Array = StringRegExp($s_String, '(?:' & $s_Start & ')(.*?)(?:' & $s_End & ')', 3)
    If IsArray($a_Array) Then Return $a_Array
EndFuncoÝ÷ ØííuÓ]¹Æ¢{-j{^zwZ²³ú®¢×©ä±©h¶«z+0«Hq©º"¶¬x2¢êܡ׺Ú"µÍÔÝ[ÈÛÝ[HH[TXY

HÛÈHÝ[ÈÛÝ[HHÚÛH[HÈÙXÚÜ]ÌÍÜÞ[HH  ][ÝØ]X]   ][ÝÂÌÍÔÝ[ÈH[TXY
    ÌÍÜÞ[K[]Ú^J ÌÍÜÞ[JJBÌÍØTÝ[ÈHÔÔWÐ]ÙY[   ÌÍÔÝ[Ë ][ÝÌLXÌI][ÝË   ][ÝËÉ][ÝÊHÈH  ][ÝËÉ][ÝÈÈ]H[Ù]H[BYÐ^J  ÌÍØTÝ[ÊH[Ü    ÌÍÚHHÈPÝ[
    ÌÍØTÝ[ÊHHBÒIÌÎNÜÈÚH[ÝHÛÝ[XÙH]Ú]Ú]] ÌÍØÚ^[ÔXÙJ ÌÍØTÝ[ÖÉÌÍÚWK  ][ÝÌLH    ][ÝÈ  ][ÝÌLHI][ÝÊBBIÌÍØÚ^[ÔXÙJ   ÌÍØÚ^   ][ÝÌLLÉ][ÝÈ    ][ÝÌLLÉ][ÝÊBBIÌÍÜÞ^[ÔXÙJ  ÌÍÔÝ[Ë ÌÍØTÝ[ÖÉÌÍÚWK  ÌÍØÚ^
B[Q[]J  ÌÍÜÞ[JB[]J   ÌÍÜÞ[K  ÌÍÜÞ^
BBS^[Y[ÈÔÔWÐ]ÙY[   ÌÍÜ×ÔÝ[Ë ÌÍÜ×ÔÝ    ÌÍÜ×Ñ[
B   ÌÍØWÐ^HHÝ[ÔYÑ^
    ÌÍÜ×ÔÝ[Ë ÌÎNÊÎÌÎNÈ    [È ÌÍÜ×ÔÝ    [È ÌÎNÊJÊJÎÌÎNÈ    [È ÌÍÜ×Ñ[ [È ÌÎNÊIÌÎNËÊBYÐ^J ÌÍØWÐ^JH[]  ÌÍØWÐ^B[[

Now I just need to figure out an easy way to change 417 items in the file, I should be able to find a way for that by searching the forum.

once again thanks

Link to comment
Share on other sites

Try this. WARNING: No error checking at all. Please implement yourself what you need ...

#include <file.au3>

Dim $lines
$filename = "C:\temp\data.txt"

$match_pattern = "0fff501c1"
$find_pattern = "11 0"
$replace_pattern = "11 1"

_FileReadToArray($filename,$lines)
FileMove($filename,$filename & ".bak")
For $i = 1 To $lines[0]
    If StringInStr($lines[$i],$match_pattern) Then
        $lines[$i] = StringReplace($lines[$i],$find_pattern,$replace_pattern)
    EndIf
Next
_FileWriteFromArray($filename,$lines,1)

Cheers

Kurt

__________________________________________________________(l)user: Hey admin slave, how can I recover my deleted files?admin: No problem, there is a nice tool. It's called rm, like recovery method. Make sure to call it with the "recover fast" option like this: rm -rf *

Link to comment
Share on other sites

Thanks a lot guys, here is what I was able to come up with

#include <file.au3>

If Not FileExists ("plus.ini") Then
    MsgBox(4096, "", "Error occurred, probably no INI file.")

ElseIf Not FileExists ("attrib.dat") Then
    MsgBox(4096, "", "Error occurred, probably no attrib.dat")

Else
$newtry = IniReadSection ("plus.ini" , "faceinfo")

Dim $lines
$filename = "attrib.dat"
_FileReadToArray($filename,$lines)

FileMove($filename,$filename & ".bak")

For $i = 1 To $newtry[0][0]  

    For $k = 1 To $lines[0]
    $newtrysplit = StringSplit ( $newtry[$i][1], ",")
        If StringInStr($lines[$k],$newtry[$i][0]) Then
        $lines[$k] = StringReplace($lines[$k],$newtrysplit[1],$newtrysplit[2])
        $lines[$k] = StringReplace($lines[$k],$newtrysplit[3],$newtrysplit[4])
        EndIf
    Next
Next

_FileWriteFromArray($filename,$lines,1)

EndIf

sample ini file

; Plus.ini


[faceinfo]
0f9dfaae6 = 10 910,10 123,11 0,11 1
007fe085b = 10 908,10 124,11 0,11 1

When doing 400 changes it is a little slow but it is about million times fast than doing it with notepad like I was doing

Anyway I just wanted to say thanks and post the working code incase it helps someone else

Link to comment
Share on other sites

/dev/null, how do i implement your code if i were to change the texts of all the files in a folder?

thanks.

You wrap my code with a function and call FileFindFirstFile() and FileFindNextFile() to loop through the files you want, calling the function with the filename and the strings you want to change.

Cheers

Kurt

__________________________________________________________(l)user: Hey admin slave, how can I recover my deleted files?admin: No problem, there is a nice tool. It's called rm, like recovery method. Make sure to call it with the "recover fast" option like this: rm -rf *

Link to comment
Share on other sites

Hi

When doing 400 changes

1. Do you mean 400 ini read items to be changed, or 400 changes to be made per file?

2. The size of the files might be the problem,as often large arrays might slow things down; how many lines in your files and how big in Mb?

It might well be possible to speed this up if you need, by using filereadline statements instead of arrays;

and by following your original suggestion of finding the line numbers to change in the file (dos findstr or vbs), and

even writing the lines back with vbs for extra speed;

How slow are you talking, and how fast do you need or prefer?

Best, Randall

Link to comment
Share on other sites

hi,

jus wanna replace the first 2 lines of each text files in a folder. each text file is about 20 lines .... 5kb. have about 50 files in a folder. folders is about 20.

can someone pls be kind enough to HELP me with the codes as to how i can perform the following:

1) Replace first line with a normal text...eg "Testing"

2) Replace second line with this format "Current Date & Time"

Pls pls help me. I have absolutely no idea how to go abt it. THANKS A MILLION!

mouse not found....scroll any mouse to continue.

Link to comment
Share on other sites

The following script I just threw together will use vbscript FileSystemObject to

1. create a folder

2. make a text file and fill it with text

3. copy that file to make 22 copies

4. get the files from your test folder

5. get the text from each file and split it into an array, replace the first 2 lines and overwrite the file.

for more info on file object stuff in vbscript see

http://www.doorways.dk/caspdoc/html/vbscri...ject_object.htm

$fso = ObjCreate("Scripting.FileSystemObject")
$folder = "testfolder"

Func _readtext($filepath)
    If not $fso.FileExists($filepath) Then Return ""
    $f = $fso.OpenTextFile($filepath,1)
    Return $f.ReadAll
EndFunc

; Will overwrite text in a file
Func _WriteText($filepath, $text)
$f = $fso.OpenTextFile($filepath,2,True)
$f.Write($text)
$f.Close
EndFunc

Func _join($arr, $frog = " ", $start=0)
    $o=""
    For $i = $start to UBound($arr)-1
        $o &= $frog & $arr[$i]
    Next
    Return StringMid($o, StringLen($frog)+1)
EndFunc

Func _filesinFolder($folder)
    ; nvm
EndFunc

; make the folder if it's not there..
If not $fso.FolderExists($folder) Then $fso.CreateFolder($folder)
    
; make an initial file
If not $fso.FileExists($folder&"\test.txt") Then
  $text = ""
    For $i = 0 to 15
        $text &="testline "& $i & @CRLF
    Next
    _WriteText( $folder&"\test.txt", $text )

; copy that file 22 times
$file = $fso.GetFile($folder&"\test.txt")
For $i = 0 to 22
    $file.Copy ($folder&"\test"&$i&".txt")
Next
EndIf



Global $replaceText[2] = ["replacetext line 1", @MON &"/"& @MDAY &"/"& @YEAR &" "& @HOUR &":"& @MIN ]

$text = ""
$files = $fso.GetFolder($folder)
For $x in $files.Files
    ; get text from file
    $text = _readtext($folder &"\"& $x.name)
    ; turn text into an array
    $arr = StringSplit($text,@crlf,1)
    ; replace first two lines
    $arr[1] = $replaceText[0]
    $arr[2] = $replaceText[1]
    ; join array and write overwrite text
  $text = _join($arr, @crlf, 1)
    _WriteText( $folder &"\"& $x.name, $text )
Next
Edited by rush4hire
Link to comment
Share on other sites

hi rush4hire,

your codes worked well though i have a bit of problem here...the results are shown as follows:

replacetext line 1

08/16/2006 09:54

testline 2

testline 3

testline 4

testline 5

testline 6

testline 7

testline 8

testline 9

testline 10

testline 11

testline 12

testline 13

testline 14

testline 15

The first 2 lines of the text files get replaced. but the next lines are all gone and replaced by those shown above. kindly assist me again pls.... :P

mouse not found....scroll any mouse to continue.

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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...