Jump to content

Search for a value in .txt file


Recommended Posts

Hi, i'd like to know if there's a way to search in all the sections in txt file for a value for ex:
i have sections like that :
[123456]
name = asdasdasd
[564665]
name = asdmfkggf
[465468]
name = askjfjgkjfd

For ex: now i wanted to search for "asdmfkggf" and delete the section of "asdmfkggf" and i also wanted to know how to replace "asdmfkggf"
thanks.

Link to comment
Share on other sites

Check the INI* functions for INIREAD, INIDELETE, INIREADSECTION and INIREADSECTIONNAMES as a start, as the format of your file is the same as an INI file.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Bro i know all of that !
What i meant is iam using random numbers for creating the section names so i don't know the name of the section to search for the value !
Thats what i meant.

Link to comment
Share on other sites

Did you read what I wrote?

IniReadSectionNames will READ the SECTION NAMES in your ini file, then you can use that to cycle through them the read the contents of each section using IniReadSection. Then you can DELETE what you want to using IniDelete.

That's how you can do it the easiest way.

Bro

 

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

  • Moderators

Create an example ini file on my desktop:

[3920934802]
1=2
2=3
3=4
[39208423]
2=3
[2304820384]
1=7
d=dog
3=4
[3902840]
k=j
3=4

I wanted to find all the sections and keys that held the value "4".

#include <Array.au3>; for _arraydisplay to show data

Global $gsIni = @DesktopDir & "\Test.ini"
Global $gsFindValue = "4"
Global $gaData = _IniSectionByValue($gsIni, $gsFindValue)
_ArrayDisplay($gaData, "Found Data")

Func _IniSectionByValue($sIni, $sValue, $bCaseSense = 0)
    ; list of section names
    Local $aSections = IniReadSectionNames($sIni)
    If Not IsArray($aSections) Then
        Return SetError(1, 0)
    EndIf

    ; well need to be able to read all the keys
    Local $aKey
    Local $iUB = UBound($aSections)

    ; well need a return array
    ; [0][0] = total ubound - 1
    ; [n][0] = section
    ; [n][1] = key
    ; [n][1] = value of key / $sValue but for case insensitive matching
    Local $aRet[$iUB][3]

    ; we need to keep track of ubound in case we need to redim
    Local $icount = 0
    Local $bmatch = False

    For $i = 1 To UBound($aSections) - 1
        $aKey = IniReadSection($sIni, $aSections[$i])
        If Not IsArray($aKey) Then
            ContinueLoop ; sanity check
        EndIf
        ; now enum through the keys to check the value match
        For $k = 1 To UBound($aKey) - 1
            If $bCaseSense Then
                If StringCompare($sValue, $aKey[$k][1]) = 0 Then
                    $bmatch = True
                EndIf
            ElseIf $sValue = $aKey[$k][1] Then
                $bmatch = True
            EndIf
            If $bmatch Then
                $icount += 1
                If $icount > $iUB - 1 Then
                    ReDim $aRet[$icount + 1][3]
                EndIf
                $aRet[$icount][0] = $aSections[$i]
                $aRet[$icount][1] = $aKey[$k][0]
                $aRet[$icount][2] = $aKey[$k][1]
            EndIf
            $bmatch = False
        Next
    Next
    If Not $icount Then
        Return SetError(2, 0)
    EndIf

    ReDim $aRet[$icount + 1][3]
    $aRet[0][0] = $icount

    Return $aRet
EndFunc

From here I can delete keys or sections by using IniDelete (where the section delete excludes the 3rd "key" parameter)

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

Is it something like this you're after?

; ini content same as SmoKE_N
Local $sText = FileRead("..\test\tst.ini")

; get list of sections containing a given value
Local $sSearched = "4"
Local $aSections = StringRegExp($sText, "(?msU)\[([^\[]+)\][^\[]*=\Q" & $sSearched & "\E", 3)
_ArrayDisplay($aSections)

; delete section containing the value "dog"
ConsoleWrite(">>> Before" & @LF & $sText & @LF)
$sSearched = "dog"
;$sText = StringRegExpReplace($sText, "(?msU)\[[^\[]+\][^\[]*=\Q" & $sSearched & "\E[^\[]*\R", "")   <<-- bug here!
$sText = StringRegExpReplace($sText, "(?msU)\[[^\[]+\][^\[]*=\Q" & $sSearched & "\E[^\[]*?\R", "")
ConsoleWrite(">>> After" & @LF & $sText & @LF)

; rename all values "3" by "three"
$sSearched = "3"
$sText = StringRegExpReplace($sText, "(?msU)(?<==)\Q" & $sSearched & "\E(?=\R|$)", "three")
ConsoleWrite(">>> Replaced" & @LF & $sText & @LF)

Matching is case-sensitive; use (?imsU) if you vant case insensitivity.

Edited by jchd
Bug fixed for delete section

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

@jchd
I noticed in your example, post #7, to delete the section with the value "dog", the keys after the found "dog" in the deleted section are add to the previous section - probably because of "(?U)".

Another example.

#include <Array.au3>

Local $sFileName = "Test99.ini"
_LoadIni($sFileName) ; Create test file

$aArr = _Ini_DisplaySectionsWithValue(FileRead($sFileName), 4)
_ArrayDisplay($aArr, "Section with Values")

MsgBox(0, "Delete Section", _Ini_DeleteSectionWithValue(FileRead($sFileName), "Dog"))

MsgBox(0, "Replace Value", _Ini_FindValueAndReplace(FileRead($sFileName), 3, "three"))

FileDelete($sFileName) ; Clean up file


Func _Ini_DisplaySectionsWithValue($sIniFileContents, $sValue)
    Local $a = StringRegExp($sIniFileContents, "(?i)\[([^\[\]]+?)\][^\[\]]*?([^\[\]\v]+)=(\Q" & $sValue & "\E)", 3) ;

    ; --------- Convert 1D array to 2D array ----------------------
    Local $iSize = UBound($a)
    Local $iCols = 3
    Local $aArray[Ceiling($iSize / $iCols)][$iCols] ; Ceiling() function used to allow for odd number of data entries.
    For $i = 0 To $iSize - 1
        $aArray[Int($i / $iCols)][Mod($i, $iCols)] = $a[$i]
    Next
    ; --------- End of Convert 1D array to 2D array ----------------------

    _ArrayInsert($aArray, 0, "Section|Key|Value")
    Return $aArray
EndFunc   ;==>_Ini_DisplaySectionsWithValue

Func _Ini_DeleteSectionWithValue($sIniFileContents, $sValue) ; With "(?i)" in the Reg Exp Pattern, matches are case insensitive.
    Return StringRegExpReplace($sIniFileContents, "(?i)\[[^\]]+\][^\[]*=\Q" & $sValue & "\E[^\[]+", "")
EndFunc   ;==>_Ini_DeleteSectionWithValue

Func _Ini_FindValueAndReplace($sIniFileContents, $sSearchValue, $sReplace, $iCount = 0)
    Return StringRegExpReplace($sIniFileContents, "(?m)(?<=\=)\Q" & $sSearchValue & "\E(?=\R|$)", $sReplace, $iCount)
EndFunc   ;==>_Ini_FindValueAndReplace

Func _LoadIni($FileName)
    Local $hFileOpen = FileOpen($FileName, 2) ;  $FO_OVERWRITE (2)
    FileWrite($hFileOpen, _
            "[3920934802]" & @CRLF & _
            "1=2" & @CRLF & _
            "2=3" & @CRLF & _
            "3=4" & @CRLF & _
            "[39208423]" & @CRLF & _
            "2=3" & @CRLF & _
            "[2304820384]" & @CRLF & _
            "1=7" & @CRLF & _
            "d=dog" & @CRLF & _
            "3=4" & @CRLF & _
            "4=3" & @CRLF & _
            "[3902840]" & @CRLF & _
            "k=j" & @CRLF & _
            "3=4")
    FileClose($hFileOpen)
    Sleep(500)
EndFunc   ;==>_LoadIni

 

Link to comment
Share on other sites

Thanks @Malkey I've fixed that overlook.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

  • 2 weeks later...

Guys i am sorry but i cannot do something that i cannot understand "i cannot understand the patterns that in stringregexp"
so is there other ways to do it ? 
for ex :
first we read the section names by $s = inireadsectionnames("test.ini")
then  $readvalue = inireadsection("test.ini",$s[$i])
and then i can make if $readvalue = "1" then give me the name of the section but i don't know how to get the name of the section ;c 
someone could help me please ?

Link to comment
Share on other sites

LerN,

#include <Array.au3>

Local $readvalue, $aSection = IniReadSectionNames(@ScriptDir & "\test.ini")

For $i = 1 To UBound($aSection) - 1
    $readvalue = IniReadSection("test.ini", $aSection[$i])
    If $readvalue[0][0] = 1 And $readvalue[1][0] = "name" And $readvalue[1][1] = "askjfjgkjfd" Then
        MsgBox(0, 'Section name is', $aSection[$i])
        _ArrayDisplay($readvalue, "read")
    EndIf
Next

 

Edited by Deye
Link to comment
Share on other sites

3 hours ago, LerN said:

"i cannot understand the patterns that in stringregexp"

Yes you can.  Just add an a to your pseudo and go do it!

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Learn

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Carefully reading the regexp (PCRE) specifications and complete documentation will help, over time. Repeat and rinse as needed.

I agree regexpes aren't completely obvious at first but reveal both perfectly logical and very powerful once you familiarize yourself with their "awkwardness".

You can "explode" a regexp pattern into plain english by pasting it in this page: RegExp
There you can feed it with input and see what result you get and you can even see it working step by step using the debug feature.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

I meant "debugging regular PCRE expressions"!

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

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...