Sign in to follow this  
Followers 0
michaelslamet

Read Text File based on a key

7 posts in this topic

So I have a text file that contain:

key1=value1

key2=value2

key3=value3

I want to create a function that return value for key I'm searching for.

I'm not really need this because I already have my code working great, but I wonder and keen to learning another ways to do it :)

I believe there must be a dozen ways to do this with less lines of codes and in higher processing speed compared to my stupid and simple code.

Func ReadTextFileBaseOnKey($fFile, $sKey)
    $iLine = 1
    $sResult = ""
    $file = fileOPen($fFile, 0)
    while 1
        $sRead2 = FileReadLine($file, $iLine)
        if @error Then
            FileClose($file)
            ExitLoop
        Else
            $sRead = FileReadLine($fFile, $iLine)
            If StringLeft($sRead, StringLen($sKey)) = $sKey then
                $sResult = StringRight($sRead, StringLen($sRead)-StringInStr($sRead,"=",0))
                ExitLoop
            EndIf
            $iLine = $iLine + 1
        EndIf
    WEnd
    FileClose($file)
    Return $sResult
EndFunc

Share this post


Link to post
Share on other sites



Hi,

Something like this I guess :

#include <Array.au3>

Local $s = "", $sKey = "", $a = 0

$s = FileRead("t.txt")

$sKey = "key3"

$sKey = StringRegExpReplace($sKey, "(\.|\||\*|\?|\+|\(|\)|\{|\}|\[|\]|\^|\$|\\)", "\\$1") ;pattern escape

$a = StringRegExp($s, $sKey & "=(.*)", 3)

_ArrayDisplay($a)
Br, FireFox.

 

OS : Win XP SP2 (32 bits) / Win 7 SP1 (64 bits) / Win 8 (64 bits) | Autoit version: latest stable / beta.
Hardware : Intel(R) Core(TM) i5-2400 CPU @ 3.10Ghz / 8 GiB RAM DDR3.

My UDFs : Skype UDF | TrayIconEx UDF | GUI Panel UDF | Excel XML UDF | Is_Pressed_UDF

My Projects : YouTube Multi-downloader | FTP Easy-UP | Lock'n | WinKill | AVICapture | Skype TM | Tap Maker | ShellNew | Scriptner | Const Replacer | FT_Pocket | Chrome theme maker

My Examples : Capture toolIP Camera | Crosshair | Draw Captured Region | Picture Screensaver | Jscreenfix | Drivetemp | Picture viewer

My Snippets : Basic TCP | Systray_GetIconIndex | Intercept End task | Winpcap various | Advanced HotKeySet | Transparent Edit control

 

Share this post


Link to post
Share on other sites

Sh*t, that RegEx seems so cool :thumbsup:

Great to know there is always more than 1 way to do something in AutoIT :)

Thanks, Firefox!

Anybody else? :D

Share this post


Link to post
Share on other sites

Add a section header to the file and you can use the Ini* functions of AutoIt like IniRead.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

yet another way ;)

#include <Array.au3>

Local $sTest = "key1 = This has some value" & @CRLF & _
        "key2 = Values cant contain equal sign" & @CRLF & _
        "key3 ! =  One equal sign per line"

Local $aRegExp = StringRegExp($sTest, "(?mU)^([^\r\n=]+)=([^=]+)$", 4)
Local $iUbound = UBound($aRegExp), $aTemp

Local $aKeys_Values[$iUbound][2]

For $i = 0 To $iUbound - 1

    $aTemp = $aRegExp[$i]
    $aKeys_Values[$i][0] = $aTemp[1] ;the key
    $aKeys_Values[$i][1] = $aTemp[2] ;the value

Next

_ArrayDisplay($aKeys_Values)
$aKeys_Values = 0
$aRegExp = 0

Though I would even recommend IniRead/Write as Water said

Regards :)


My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

If you have full control over the text file content, then I would do as water suggests ... that's if it hasn't got header/s already, which would make it even easier.

Working with .ini files, is quick, simple and easy.

If you had to or wanted to, you could even duplicate any text file, placing a subject header in the local copy first ... that's if you had to leave the original as is.

The beauty with an ini file, apart from simplicity of interaction, is that you can use one file like so ->

 

[Header 1]

key1=value1

key2=value2

key3=value3

[Header 2]

key1=value1

key2=value2

key3=value3

[Header 3]

key1=value1

key2=value2

key3=value3

 

If you didn't have the equals sign though, I would recommend going the route the others suggested.

Edited by TheSaint

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Share this post


Link to post
Share on other sites

@Water: thanks for the idea for using ini file. That will be much convinience and easier.

@TheSaint: thanks for showing another way of using ini file. Yes, I have the equals sign :)

@PhoenixXL: thanks for showing another way using that using RegEx :)

Share this post


Link to post
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
Sign in to follow this  
Followers 0