Dimitric

Extract a character string

17 posts in this topic

#1 ·  Posted (edited)

Hello everyone,

 i got a problem when i want to extract a caracter string from my logfile.

 

in my scripts i use $logfile and when the users enter all the choice to install some program or configure the PC the script write in the logfile what he did.

on my first test it write if the user say Yes, No or Continue and it write in the logfile this : 2015-09-22 09:01:45 : Yes (it's in french hours and date)

so i want to know how i can just take the Yes, no or Continue from my logfile. I just checked in the help of scite and i only found -filereadline but it don't work for it.

 

I got an other question it's after extract my character, i want to know if i can use the extraction directly after or i need to put the extraction in a variable. like if i do this test :

If _filereadline = "Yes" then Case1 ... i know the test is wrong, but in my idea it work like this.

 

thanks you for your help, and sorry for my bad english, i really need to improve it.

 

Best regards.

Edited by dimitricervantes

Share this post


Link to post
Share on other sites



dimitricervantes,

Welcome to the AutoIt forums.

Extracting the required "Yes/No/Continue" from the line is very easy, but we need a little more information before we can suggest the best way to do it. For example, how do you determine WHICH line you need to read? Is it based on the timestamp? The content of a previous line? Or something else?

The best way forward is for you to attach a sample file (or an extract of several lines) and explain exactly how to determine the line we need to parse - then we can look at how to identify it correctly and extract the data you require.

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

Hi,

 

i don't need to know wich line i need to extract because when i want to extract my information i only have 1 line (it's at the beginning of my script) in my logfile.

 

look :

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $Continuer
            _FileWriteLog($LogFile,"Continuer")
            FileCopy($Ressources & "Auto_install_suite.bat", @StartupDir & "\Auto_install_suite.bat") ;==> Copie le .bat dans startup
            Shutdown(6)
        Case $Non
            _FileWriteLog($LogFile,"Non")
            MsgBox(0, "Auto-Install -GV-", "Sortie du programme...")
            exit
        Case $Oui
            _FileWriteLog($LogFile,"Oui")
            ;==> Renomme le pc en utilisant le nom du compte connecté + Groupe de travail
            _FileWriteLog($LogFile,"Début changement nom pc")
            $CompName = @UserName
            RegWrite ("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Computername\Computername", "Computername", "REG_SZ", $CompName)
            RegWrite ("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Computername\ActiveComputername", "Computername", "REG_SZ", $CompName)
            RegWrite ("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters", "Hostname", "REG_SZ", $CompName)
            RegWrite ("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters", "NV Hostname", "REG_SZ", $CompName)
            RegWrite ("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "AltDefaultDomainName", "REG_SZ", $CompName)
            RegWrite ("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "DefaultDomainName", "REG_SZ", $CompName)
            RegWrite ("HKEY_USERS\.Default\Software\Microsoft\Windows Media\WMSDK\General", "Computername", "REG_SZ", $CompName)
            ;==> Fin renommage pc + Groupe de travail
            DllCall("Netapi32.dll", "long", "NetJoinDomain", "int", 0, "wstr", "CVINCENT", "int", 0, "int", 0, "int", 0, "dword", 0x00000040) ;==> Modifie le groupe de travail
            _FileWriteLog($LogFile,"Fin changement nom pc")
            $REP_CompName2 = MsgBox(4, "Auto-Install -GV-", "Modification effectuée, OUI pour redémarrer ou NON pour faire autre chose...")
            If $REP_CompName2 = 6 Then
                FileCopy($Ressources & "Auto_install_suite.bat", @StartupDir & "\Auto_install_suite.bat") ;==> Copie le .bat dans startup
                Shutdown(6)
            Else
                $REP_CompName3 = MsgBox(4, "Auto-Install -GV-", "Continuer le script au prochain démarrage ?")
                If $REP_CompName3 = 6 Then
                    Exit
                Else
                    FileDelete(@StartupDir & "\Auto_install_suite.bat")
                    Exit
                EndIf
            EndIf
        Exit

    EndSwitch
WEnd

that's in french so sorry about it, that's in my pre-script if i can call him like that, if you like just after the case $continuer you can see the

_FileWriteLog($LogFile,"Continuer")

that write in my logfile my information so there is only this for now. (But if i write something more in my logfile it will be in line 2, the info i need is still line 1).

 

After when i go on my second scripts (auto_install_suite.au3) i want to extract only the Yes/No/Continue from the logfile and that what i don't know how to do it, i know how to extract an entire line, but not only Yes/no/continue.

Share this post


Link to post
Share on other sites

dimitricervantes,

That makes it clear. So all you need to do is read the first line of the file and then extract the data after the timestamp.

I would do it like this:

#include <MsgBoxConstants.au3>


; Define log file to read
$sLogFile = "LogFile.txt"

; Read first line
$sLine = FileReadLine($sLogFile, 1)

; Extract data from the line
$sData = StringRegExpReplace($sLine, "^.*\s:\s(.*)$", "$1")


; And display it
MsgBox($MB_SYSTEMMODAL, "", $sData)

which works just fine with this dummy file:

2015-09-22 09:01:45 : Yes
2015-09-22 09:01:50 : Line 2
2015-09-22 09:01:51 : Line 3
2015-09-22 09:01:52 : Line 4

The RegEx just extracts whatever is after the final colon on the line. You could also use StringSplit, but a RegEx is quicker.

Please ask if you have any questions.

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

Since the timestamp is fixed format you can just use StringTrimLeft as well.


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)

Share this post


Link to post
Share on other sites

Great, i'm going to test it thank you.

but can i use the data that have been extracted on :

; Extract data from the line
$sData = StringRegExpReplace($sLine, "^.*\s:\s(.*)$", "$1")

without displayed it ? like i tried to explain at the end of my last message.

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

Since the timestamp is fixed format you can just use StringTrimLeft as well.

Wow i tried it it work pretty nice !

But how can i put the extracted data in a variable ?

 

edit : forget about it, it go in a variable by default.

Edited by dimitricervantes

Share this post


Link to post
Share on other sites
Local $MyVar = StringTrimLeft(FileReadLine("my.log"), 22)

should 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)

Share this post


Link to post
Share on other sites
Local $MyVar = StringTrimLeft(FileReadLine("my.log"), 22)

should do it.

I used it and adapted to my scripts, it work perfectly ! Thank you my friend !

@Melba23 i used what you give me, it work too (pretty nice i have to say), and i thank you again, but the solution of  jchd is shortly so i will use it.

 

Thank you to both to help me.

Share this post


Link to post
Share on other sites

dimitricervantes,

No problem. I forgot to apply the first law of RegExs - do not use them when there is no need to do so!

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

Well i just spoke with my boss, and he tell me the solution of jchd will work, for a time.

 

he tell me if we change the timestamp or if we add something on the logfile (like the PC name if we put the logfile on the server) it will not work properly (i need to do a code that can be improve without change anything), so i need to do a caracter search in my logfile, like your solution @Melba23 right ?

Share this post


Link to post
Share on other sites

dimitricervantes,

Indeed so - the StringTrimLeft solution only works because there are always a fixed number of characters before the data you wish to extract. If the number of characters can vary then you will need a RegEx to find the correct point to break the line.

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

vincend,

StringInStr returns the position of the found string, not the string itself, so $MyVar would just contain an integer, not the value required.

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

dimitricervantes,

Indeed so - the StringTrimLeft solution only works because there are always a fixed number of characters before the data you wish to extract. If the number of characters can vary then you will need a RegEx to find the correct point to break the line.

M23

Yes that's it, so i'm going to use your solution at the end :D

 

Like this ?

Local $MyVar = StringInStr(FileReadLine("mylog.log"), "yes")
If $MyVar > 0 Then MsgBox(0,"",$MyVar)

 

Your solution seems working,  it search my character in logfile right ?

Share this post


Link to post
Share on other sites

dimitricervantes,

After your PM (and please do not do it again) I realise that I did not explain the RegEx - sorry about that:

^      - Start of line
 .*     - All characters until we find
 \s:\s  - space : space
 (.*)   - Capture the characters until
 $      - end of line
 
 $1     - replace it all with the captured group

So we capture what is after the final " : " and only return that. Does it make sense now?

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

Yes, it's clear now, thank you !

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