Jump to content
Sign in to follow this  
rkr

To read a line based on string search from a text file

Recommended Posts

Hi, i want to read a particular string from a text file using autoit. i wish to read it without explicitly opening the text file. the copied string should be then transferred to an excelbook (again, no need to explicitly open the excel book)... 

with reference to my screenshot attached, my input to the  'script'' is going to be 0017-0008, and the script should copy the highlighted two lines from the input file to excel

thanks

input.png

Share this post


Link to post
Share on other sites

@rkr Good morning, and welcome to the AutoIt forum :)
The best thing I should do is read the content of the file, and then parse it in order to find what you were looking for.
Then, if you match something, you can take the line/lines matched, and paste in a new file.
In the help, look for File* and _File* functions, to have an idea of what they do :)

Feel free to ask if you need any help!

Francesco

Edited by FrancescoDiMuro

Click here to see my signature:

Spoiler

Thoughts:

  • I will always thank you for the time you spent for me.
    I'm here to ask, and from your response, I'd like to learn.
    By my knowledge, I can help someone else, and "that someone" could help in turn another, and so on.

/*--------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

ALWAYS GOOD TO READ:

 

Share this post


Link to post
Share on other sites

@rkr , We can help you if you can provide textfile to parsed and a sample code that we can start with.

To give hint of what FrancescoDiMuro means is this "Local $aSection = IniReadSectionNames(@ScriptDir & "\test.txt")" or "Local $var = IniReadSection(@ScriptDir & "\Testing.txt", $sValue)" and then go for "For $i = 1 To $var[0][0]... Next" to get the array from IniReadSection(). With that maybe you can start checking our help file.

You can start with this.

Local $sValue = InputBox("Testing", "Value to search...", "") ;value to search in text file
Local $var = IniReadSection(@ScriptDir & "\Testing.txt", $sValue)
If @error Then
    MsgBox(4096, "", "Error occurred, probably no INI/TEXT file.")
Else
    For $i = 1 To $var[0][0]
        MsgBox(4096, "", "Key: " & $var[$i][0] & @CRLF & "Value: " & $var[$i][1]) ;display the array
    Next
EndIf

in Text file data is:

[0017-0008]
0017
0008

Or

#include <Array.au3>

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

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 ; input to search in text file, you can also change this to InputBox().
        MsgBox(0, 'Section name is', $aSection[$i]); check if input is correct
        _ArrayDisplay($readvalue, "read"); display the array from $readvalue
    EndIf
Next

in Text file data is:

[123456]
name = asdasdasd
[564665]
name = asdmfkggf
[465468]
name = askjfjgkjfd

Else, let us know further for your needs.

 

KS15


Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites


 @KickStarter15, thanks for that detail help.. i tried the code, but i am getting error message - but the file is in the same location  - tried _filecountlines and it worked perfectly - which means the error is not due to lack of access. i am attaching the text file (gaplst.) and the script with this. could you please have a look.. thanks

copychunk.au3

gaplst

Share this post


Link to post
Share on other sites

@rkr,

Try this and try playing with it.^_^

#include <File.au3>

Dim $array

$file = @ScriptDir & "\gaplst.txt"
$find = InputBox('What To Find', 'Type in below what to search for.' & @CRLF & _
        'Lines that match will be shown.', 'Text To Match', '', 200, 140)
$found = 0
$lines = ''

If $file <> '' And $find <> '' Then
    _FileReadToArray($file, $array)
    For $i = 1 To UBound($array) - 1
        If StringInStr($array[$i], $find) Then
            $array[$i] = ''
            $found += 1
            $lines &= $i & ', '
        EndIf
    Next
    MsgBox(64, 'Done', 'Total lines found = ' & $found & @CRLF & _
            'Searched Line(s)= ' & FileReadLine($file, $lines))
    $sFile = @ScriptDir & '\New.txt'
    $hFile = FileOpen($sFile, $FO_APPEND)
    FileWrite($hFile, FileReadLine($file, $lines)) ; to see if the line is correct
    FileClose($hFile)
Else
    MsgBox(48, 'Error', 'A file was not picked or what to find was cancelled/empty!')
EndIf

Also, as noticed with your text file, member name is not unique it is repeatedly occurring in the text file, so better to search the unique member name to show your input.

Example:

You want yo search for 0017-0008... then it should as this "0017-0008 0017 L2A" to show the data you wanted. I'll check on this later that it can only show the data you wanted but for now, you can play with it.;)

 

 

KS15

Edited by KickStarter15

Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites
On 1/19/2018 at 7:21 AM, KickStarter15 said:

@rkr,

Try this and try playing with it.^_^

#include <File.au3>

Dim $array

$file = @ScriptDir & "\gaplst.txt"
$find = InputBox('What To Find', 'Type in below what to search for.' & @CRLF & _
        'Lines that match will be shown.', 'Text To Match', '', 200, 140)
$found = 0
$lines = ''

If $file <> '' And $find <> '' Then
    _FileReadToArray($file, $array)
    For $i = 1 To UBound($array) - 1
        If StringInStr($array[$i], $find) Then
            $array[$i] = ''
            $found += 1
            $lines &= $i & ', '
        EndIf
    Next
    MsgBox(64, 'Done', 'Total lines found = ' & $found & @CRLF & _
            'Searched Line(s)= ' & FileReadLine($file, $lines))
    $sFile = @ScriptDir & '\New.txt'
    $hFile = FileOpen($sFile, $FO_APPEND)
    FileWrite($hFile, FileReadLine($file, $lines)) ; to see if the line is correct
    FileClose($hFile)
Else
    MsgBox(48, 'Error', 'A file was not picked or what to find was cancelled/empty!')
EndIf

Also, as noticed with your text file, member name is not unique it is repeatedly occurring in the text file, so better to search the unique member name to show your input.

Example:

You want yo search for 0017-0008... then it should as this "0017-0008 0017 L2A" to show the data you wanted. I'll check on this later that it can only show the data you wanted but for now, you can play with it.;)

 

 

KS15

thanks a lot KS15, that was to the point..helped me

Share this post


Link to post
Share on other sites
On 1/21/2018 at 2:23 PM, rkr said:

thanks a lot KS15, that was to the point..helped me

I want to help you but not much that I can do with your application. Maybe there are other coder here that knows how to deal with this.

As for the head start, you can check my code below. Note: Member name is unique and as you've noticed, I added letter 'a' in member number '0017-0008a' to see if the code worked (attached). Take a test on this:

First code is to loop thru your text file and find all the occurrences of the searched number.

#include <File.au3>

Dim $array, $sLine

$file = @ScriptDir & "\gaplst.txt"
$find = InputBox('What To Find', 'Type in below what to search for.' & @CRLF & _
        'Member Number:', 'Text To Match', '', 200, 140)
$found = 0
$lines = ''

If $file <> '' And $find <> '' Then
    _FileReadToArray($file, $array)
    For $i = 1 To UBound($array) - 1
        If StringInStr($sLine, $find) And Not $iValid Then
            $iValid = 1
            ContinueLoop
        EndIf
        If StringInStr($array[$i], $find) Then
            $array[$i] = ''
            $found += 1
            $lines &= $i & ', '
            $sLine = MsgBox(4, 'Done', 'Total lines found = ' & $found & @CRLF & _
                  'Searched Line(s)= ' & FileReadLine($file, $i) & @CRLF & @CRLF & _
                  'Proceed searching.')
            $sFile = @ScriptDir & '\New.txt'
            $hFile = FileOpen($sFile, $FO_APPEND)
            $sLine = FileReadLine($hFile)
            FileWrite($hFile, FileReadLine($file, $i) & @CRLF)
            FileClose($hFile)
         ElseIf $sLine = 7 Then
           Exit
        EndIf
    Next
   Else
    MsgBox(48, 'Error', 'A file was not picked or what to find was cancelled/empty!')
EndIf

 

The next code is to get what you need to be searched but again it needs to be unique like letter "a" was added in the searched number. ConsoleWrite() will show you the results.:sweating:

#include <File.au3>
#include <Array.au3>

Dim $array

$find = InputBox('What To Find', 'Type in below what to search for.' & @CRLF & _
        'Member Number:', 'Text To Match', '', 200, 140)

Global $file = @ScriptDir & "\Testing.txt", $find
Global $iLine = 1, $sLine = '', $iValid = 0
Global $hFile = FileOpen($file)

$found = 0
$lines = ''

If $hFile = -1 Then
    MsgBox(0,'ERROR','Unable to open file for reading.')
    Exit 1
EndIf
If $file <> '' And $find <> '' Then
    _FileReadToArray($file, $array)
    For $i = 1 To UBound($array) - 1
        If StringInStr($array[$i], $find) Then
            Global $iLine = 0, $sLine = '', $iValid = 0
            $array[$i] = ''
            $found += 1
            $lines &= $i & ', '
            ConsoleWrite(FileReadLine($file, $i) & @CRLF)
        EndIf
    Next
   Else
    MsgBox(48, 'Error', 'A file was not picked or what to find was cancelled/empty!')
EndIf

; do a loop to locate the next line of $find
While 1
    $iLine += 1
    $sLine = FileReadLine($hFile)
    If @error = -1 Then ExitLoop

    ; test the line for the $search string until the flag $iValid is set
    If StringInStr($sLine, $find) And Not $iValid Then
        $iValid = 1
        ContinueLoop
    EndIf

    If $iValid Then
        $iValid += 1
        ConsoleWrite($sLine & @CRLF) ; To check if the search lines are correct. NOTE: It should be unique, else I have nothing to do.
        If $iValid > 5 Then ExitLoop
    EndIf
WEnd
FileClose($hFile)

Hope you can get an idea with these codes.^_^

 

Code2 text file.PNG


Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites

thanks for all that KS15, just one more doubt.. i stored the following line into an array

0017-0008  0017  l2a  1  -18407.00    5110.90    0.00    0.03    -70735.59

 

i was trying stringsplit to store each of them above as a vairable

ie; $string1 should be 0017-0008,

$string2 =0017,

$string3=l2a,

 $string4=1

$string5=-18407.00 and so on till $string9

 

how do i achieve this as the delimitter in this case is not a constant... in all cases, there will be 'space' between the strings/numbers, however, the number of spaces change depending on the number, sign of number etc.. 

 

thanks for all the help

 

Share this post


Link to post
Share on other sites

What about the regular expression way ?  :)

#Include <Array.au3>

$n = "0017-0008"

; get the line to a string
; assuming that in the file, it's the last line containing "0017-0008"
$txt = FileRead("gaplst.txt")
$res1 = StringRegExpReplace($txt, '(?s).*(' & $n & '\N+).*', "$1")
Msgbox(0,"", $res1)

; parse non whitespace sequences to an array
$res2 = StringRegExp($res1, '\S+', 3)
_ArrayDisplay($res2)

 

Share this post


Link to post
Share on other sites

@rkr,

Use it this way.

_StringSplit()

Func _StringSplit()
    Local $sString = StringSplit("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59", " ") ; Split the string using the delimiter " " and return the value.

    For $i = 1 To $sString[0]
        MsgBox(0, "", "String [" & $i & "] - " & $sString[$i])
    Next
EndFunc

All you need to do is replace the "$sString" with the line searched from my above posted second code.


Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites
18 hours ago, rkr said:

i was trying stringsplit to store each of them above as a vairable

$NumberOfVars = _StringSplitToVar("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59" , " ")

For $k = 1 to $NumberOfVars
    msgbox(0, '' , eval("StringToVar" & $k))
Next


Func _StringSplitToVar($sStr , $delim)
    Local $aString = StringSplit($sStr , $delim)

    For $i = 1 To $aString[0]
        assign("StringToVar" & $i , $aString[$i] , 2)
    Next

    return $aString[0]

EndFunc

 


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites
On 1/23/2018 at 7:38 AM, iamtheky said:
$NumberOfVars = _StringSplitToVar("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59" , " ")

For $k = 1 to $NumberOfVars
    msgbox(0, '' , eval("StringToVar" & $k))
Next


Func _StringSplitToVar($sStr , $delim)
    Local $aString = StringSplit($sStr , $delim)

    For $i = 1 To $aString[0]
        assign("StringToVar" & $i , $aString[$i] , 2)
    Next

    return $aString[0]

EndFunc

 

u nailed it....thanks.. but the spacing between the numbers are not same...and it varies

Edited by rkr
noticed that input is edited

Share this post


Link to post
Share on other sites
3 hours ago, rkr said:

the spacing between the numbers are not same...and it varies

So, the regex way... because it allows such a variation

$NumberOfVars = _StringSplitToVar("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59" , "\S+")

For $k = 0 to $NumberOfVars
    msgbox(0, '' , eval("StringToVar" & $k))
Next

Func _StringSplitToVar($sStr , $what_to_get)
    Local $aString = StringRegExp($sStr , $what_to_get, 3)

    For $i = 0 To UBound($aString)-1
        assign("StringToVar" & $i , $aString[$i] , 2)
    Next
    return UBound($aString)-1
EndFunc

 

Share this post


Link to post
Share on other sites
On ‎1‎/‎23‎/‎2018 at 7:38 AM, iamtheky said:
$NumberOfVars = _StringSplitToVar("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59" , " ")

For $k = 1 to $NumberOfVars
    msgbox(0, '' , eval("StringToVar" & $k))
Next


Func _StringSplitToVar($sStr , $delim)
    Local $aString = StringSplit($sStr , $delim)

    For $i = 1 To $aString[0]
        assign("StringToVar" & $i , $aString[$i] , 2)
    Next

    return $aString[0]

EndFunc

 

thanks buddy, this helped me

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  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By cruisepandey
      Hi, 
      I have a string like this : 
      Global $Msga = "urrent directory is /send.  (Submission of file with log number 29381077284 is confirmed)";
      I want to extract the number 29381077284  from the string. I did StringSplit to split based on "(" and then use space to reach there, But it's not a good choice. 
      Can anyone help me with regular expression to find the number from String using AutoIT. TIA
    • By DannyJ
      I have this example string:
       
      2020-06-08 09:23:33 : abcdefghifjklm How to trim just the right part? Or how to trim this text right to left?
      I want to trim this string right to left until ' : '.
      In ohter words: I need the 'abcdefghifklm' text.
      I have tried StringTrimRight, but that requires 
      The number of characters to trim. Unfortunately StringSplit trims the left part of the strings.
       
       
    • By careca
      This is my take on string triggers, triggers on specific strings.
      Able to simple text pasting,
      opening links (as long as there's a www. http:\\ or https:\\ at the beggining)
      and is able to open applications, if there is a parameter in the parameter field, it uses it.
      Shows your external, lan, and gateway ip's.
      Able to change system volume by a set percentage, reading from the inputbox the number the user sets, if 0 or empty uses system default.
      I made this because the existing string trigger applications didn't do it for me.
      I did this for me, but if someone finds it useful, all the better.
    • By Colduction
      Hi guys!, i have a problem to convert Python code to AutoIt code, in fact i had not coded with Python yet!, this code is about permutation a string's case, i will be happy with your comments :)❤;

      Python code:
       
      # Python code to print all permutations # with respect to cases # Function to generate permutations def permute(inp): n = len(inp) # Number of permutations is 2^n mx = 1 << n # Converting string to lower case inp = inp.lower() # Using all subsequences and permuting them for i in range(mx): # If j-th bit is set, we convert it to upper case combination = [k for k in inp] for j in range(n): if (((i >> j) & 1) == 1): combination[j] = inp[j].upper() temp = "" # Printing current combination for i in combination: temp += i print(temp), # Driver code permute("Hello") # This code is contributed by Sachin Bisht
      My code in AutoIt:
      ; https://www.geeksforgeeks.org/permute-string-changing-case/ _PermuteCase("ABC") Func _PermuteCase($sText) If StringRegExp($sText, "^[A-Za-z]{1,}$") Then Local $iLength = StringLen($sText) ; Get length of the text. Local $iMaxPerm = 2 ^ $iLength ; Number of permutations is 2^n Local $sLow_Text = StringLower($sText) ; Converting string to lower case Local $asChrs = StringToASCIIArray($sLow_Text) ; Split the text into array of chars. For $i = 1 To $iMaxPerm Step 1 For $j = 0 To $asChrs[0] ;................................................... Next Next Else Return SetError(-1, 0, "Error: Input is incorrect!") EndIf EndFunc ;==>_PermuteCase  
       
       
       
       
       
      ====================== SOLUTION by @TheXman ======================
       
    • By jmp
      i am trying to get number from string using this code :
      #include <IE.au3> $oIE = _IEAttach ("Edu.corner") Local $aName = "Student name & Code:", $iaName = "0" Local $oTds = _IETagNameGetCollection($oIE, "td") For $oTd In $oTds If $oTd.InnerText = $aName Then $iaName = $oTd.NextElementSibling.InnerText $iGet = StringRegExpReplace($iaName, "\D", "") EndIf Next MsgBox(0, "", $iGet) it was get number like 52503058
      But, I want to get only student code 5250. (Different student have different code, sometime its 3 digits, Sometime 4)

       
×
×
  • Create New...