MrSparty1995

How do you read strings in a file, if they contain quotes already?

8 posts in this topic

#1 ·  Posted (edited)

I have a good handle on how to read a file line by line, and search for a given string.

Basically using, FileOpen, FileReadLine, and StringInStr.

I have been trying to figure out why my search keeps coming back with no match.

For example, if my string line was "Where is Waldy", and I was searching for Waldy that comes back fine.

But in my file, Let's say it is

Where is "Waldy"

So i read that line in and do a search for Waldy, but i comes back with no match since there is quotes around it.

Is there a way to resolve this?

Here is my actual example

The line comes back like this

    <JposEntry logicalName="LineDisp_iSC480">

I'm searching for LineDisp_iSC480, but its coming back with no match due to the quotes.

Thanks in advance, James

Edited by MrSparty1995
adding a better example

Share this post


Link to post
Share on other sites




While 1
    ; read each line from a file
    $line_read = FileReadLine($handle_read)
    ; exit the loop if end of file
    If @error Then ExitLoop
   ; write to the ini file
   if StringInStr($line_read, "LineDisp_iSC480") = 1 Then
      MsgBox(0, "Result", "LineDisp_iSC480 was found, no need to append")

When I do a FileReadLine

It looks like this

   <JposEntry logicalName="LineDisp_iSC480">

When I do the above search, it comes back with no match

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

It isn't that hard to make a snippet that one can actually run! ;)

Have a look at this one:

FileDelete("test.txt")
FileWriteLine("test.txt", ' <JposEntry logicalName="LineDisp_iSC480">')

$handle_read = FileOpen("test.txt")

While 1
    ; read each line from a file
    $line_read = FileReadLine($handle_read)
    ; exit the loop if end of file
    If @error Then ExitLoop
    ; write to the ini file
    If StringInStr($line_read, "LineDisp_iSC480") Then
        MsgBox(0, "Result", "LineDisp_iSC480 was found, no need to append")
    EndIf
WEnd

Jos

Edited by Jos

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites

I have attached them.  I'm not 100% done with the script yet, but got hung up on the search that isn't working.

Thanks, James

isc480.txt

isc480ijposXMLUpdate.au3

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

@MrSparty1995 (let's hope that doesn't mean you're an MSU fan) Based on your text file, this works just fine for me

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

Local $aArray
_FileReadToArray(<path to text file>, $aArray)
    For $i = 1 To $aArray[0]
        If StringInStr($aArray[$i], '<JposEntry logicalName="LineDisp_iSC480">') Then
            ConsoleWrite("Found what I was looking for on line: " & $i & @CRLF)
        EndIf
    Next

Also moved to proper forum

Edited by JLogan3o13

√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

@MrSparty1995 StringInStr returns the number where the item is found, so in your example LineDisp_iSC480 equals 29 not 1 :D, just remove the " = 1" and it should work without any issue.

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

Nice thank you!! the _FileReadToArray works :)

Edited by MrSparty1995
better information put in

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

  • Similar Content

    • Jibberish
      By Jibberish
      Junior Programmer here... 
      Not much experience with opening, changing and closing files.
      I am trying to replace strings in a Text file except StringReplace does not actually replace the text.
      Here is a sample of my code...
      #include <File.au3> #include <MsgBoxConstants.au3> #include <WinAPIFiles.au3> Local $iStrReturn = 0 Local $hFile Local $sText Local $sNewText ; Location of File to be read $sFileName = "C:\Temp\MyPlayer.exe.config" ; The default is FALSE. We want to change this to TRUE $bLoopChecked = True CheckBox() Func Checkbox() $hFile = FileOpen($sFileName,$FO_READ) ; Open file in read mode to get text If $hFile = -1 Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred when Opening the file.") Exit EndIf FileSetPos($hFile, 0, 0) ; No idea if I need to do this, grasping at straws $sText = FileRead($hFile) ; Read the file into $sText If $sText = 1 Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading/writing the file.") Exit Else FileClose($hFile) ; Finished reading the file into $sText, so close the file. FileFlush($hFile) ; Manual says to use FileFlush between File Close and Open so here it is EndIf MsgBox(0,"Before Replacement",$sText) ; Displays the text read from the file to make sure something is there. ; Loop Check If $bLoopChecked = True Then ; Find the string return > 0 for success $iStrReturn = StringInStr('"<add key="LoopCheckbox" value=""False" />"', "False") ;MsgBox(0,"", "LoopCheckBox is " & $iStrReturn) If $iStrReturn > 0 Then ; If StringInStr returned > 0 the it found the string! ; The Meat of the code. This is where we have to replace "False" with "True" $sNewText = StringReplace($sText, '"<add key="LoopCheckbox" value="False" />"', '"<add key="LoopCheckbox" value="True" />"') MsgBox(0,"After Replacement",$sNewText) ; Display the text to see if it worked. $hFile = FileOpen($sFileName,$FO_OVERWRITE) ; Reopen the file to write to it, overwriting everything. FileWrite($hFile,$sNewText) ; Write the text to the file FileClose($hFile) ; Close the file EndIf EndIf EndFunc This is the file I am reading...
      <?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/> </startup> <appSettings> <add key="LoopCheckbox" value="false"/> </appSettings> </configuration> I tried opening the file with $FO_UTF8 and $FO_UTF8_NOBOM but got errors opening the file.
      The MsgBox "After Replacement" shows the value is still false.
    • LoneWolf_2106
      By LoneWolf_2106
      Hi everybody,
      i have a log file with several entries like the following one:
      INFO [26.04.2017 11:37:48] [main] XML-Data: <online-activation> <general> <userid>XYZ</userid> <mac-address/> <OU>VG-DE</OU> <ROLE>KDT</ROLE> <FOA>PRO;FC;DOM;MDD</FOA> <BRD>XYZ;IMP</BRD> </general> <applications> <app expiration-date="2017-10-01" name="BB-INFO"/> <app expiration-date="2017-10-01" name="MMSKD"/> <app expiration-date="2017-10-01" name="FM-TOOL"/> <app expiration-date="2017-04-05" name="WEB-BTD"/> <app expiration-date="2017-10-01" name="OFFLINE-BTD"/> <app expiration-date="2017-10-01" name="MDU-UPD"/> <app expiration-date="2017-10-01" name="MDU"/> <app expiration-date="2017-04-05" name="WEB-WDA"/> <app expiration-date="2017-04-05" name="WEB-ETD"/> <app expiration-date="2017-10-01" name="OFFLINE-WDA"/> <app expiration-date="2017-10-01" name="OFFLINE-ETD"/> </applications> </online-activation>  
      I need to collect all the XML-Data, my search doesn't work:
       
      Func FileSearch() $j=0 For $i = 0 To UBound($content_array) - 1 $search_result=StringInStr($content_array[$i],$search) If $search_result<>0 Then ReDim $searchResultArray[UBound($searchResultArray) + 1] $searchResultArray [$j] = $content_array[$i] _ArrayDisplay($searchResultArray) $j+=1 EndIf Next EndFunc If i search for "online-activation", it retrieves only the first and the last tag, but not what is within.
      In addition, when i use FileReadToArray, all the entries between <online-activation> and </online-activation>

    • num1g8rfan
      By num1g8rfan
      Hi All,
      I have a script whose sole purpose is to walk through about 15,000 - 20,000 files in a single directory structure, making modifications to 5 or 6 lines within each file.  Simple.  I have a small splash screen that is simply counting how many files have been completed out of the overall total.  The script is functioning fine and the splash screams through the initial files, but through time begins to slow to a crawl (It becomes noticeable after about 1,000 to 1,500 files).  
      I have used a combination of methods to write to the file, but none of which appear to make much of any difference:
      Local $FileOpen = FileOpen($FileInList,1) FileWriteLine($FileOpen,@CRLF) FileClose($FileOpen) OR
      FileWriteLine($FileHandle, $NewLineString & @CRLF) OR
      Local $FileHandle = FileOpen($FileInList,2) _FileWriteFromArray($FileHandle,$FileContentArray,1) FileClose($FileHandle) I have checked and the CPU and memory are fine.  My current work-around is to create 5-10 separate directory structures from the original one that contains 20,000 files, run the script and then combine them again in the end.  It works, but isn't very portable.  Any ideas?
      Cleanup_AutoITPost.au3
    • fmlk
      By fmlk
      Hello,
      In a main script I have added logging and that is working. Now I created another small script where I need also logging. So I used the same code:
      What is wrong? Why is the logfile not created?

      $default_delay = 2000
      $logFilePath = ("C:\AutoIT_TestLogs")
      DirCreate($logFilePath)
      $Logfile = FileOpen($logFilePath & "\GMS_install" & @MON & "/" & @MDAY & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC & ".log",1)
      FileWriteLine($logFile,@CR & @MON & "/" & @MDAY & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC & "_Install_licenses")
      Consolewrite("Install_licenses" & @CR)
      Run("C:\Users\factory\Desktop\LicenseInstaller\LicenseInstaller.exe","C:\Users\factory\Desktop\LicenseInstaller")
      Sleep(1000)
      WinWait("Gatan License Installer")
      WinActivate("Gatan License Installer")
      WinWaitActive("Gatan License Installer")
      ControlClick("[ACTIVE]","","[NAME:CMD_Install]")
      Sleep($default_delay)
       If WinExists("LicenseInstaller") Then
           WinActivate("LicenseInstaller")
            WinWaitActive("LicenseInstaller")
            ControlClick("[ACTIVE]","","[CLASS:Button; INSTANCE:1]")
              sleep($default_delay)
         EndIf
      FileWriteLine($logFile,@CR & @MON & "/" & @MDAY & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC & "_Licenses_Installed")
      Consolewrite("Licenses are installed" & @CR)
       
    • Duck
      By Duck
      I'm attempting to read each line of a word document and assign the line to a variable. Similarly to how you can read a line from a text file (.txt or .csv) using FileReadLine(). So far i have been unsuccessful in reading from a .doc/.docx file, nor have i found any documentation that has helped.

      In searching for a solution i did find a function to convert the word doc to a text file, however my script is for (PCI) auditing purposes and i do not want to create a new file on the HDD.  I have also read through the _Word UDF help files... Unless im not understanding the _Word UDF correctly, I did not see anything that functions similarly to the FileReadLine function.
      Any help/advice is greatly appreciated!  
       
      Here is what i have been attempting to do(doesn't work): 
       
      #include <file.au3> #include <Array.au3> #include <LuhnCheck.au3> #include <Excel.au3> #include <Word.au3> Global $sPath = 'C:\Users\' Global $filePath Global $pii = @ScriptDir & '\pii_CreditCard.csv' Global $filesArray = _FileListToArrayRec($sPath , '*.txt;*.csv;*.doc;*.docx;*.xls;*.xlsx',1,1,0,2) For $i = 1 to $filesArray[0] ;Loop through file extensions and add files to the fileArray ;Assign the position in the filesArray to filePath (filePath is set to full path in FileListToArrayRec) $filePath = $filesArray[$i] readFile($filePath) Next Func readFile($file) If StringInStr($file, '.txt') Or StringInStr($file, '.csv') Then ; .txt file readTxtFile($file) ElseIf StringInStr($file, '.doc') Then ; .doc & .docx files ;============================================== part that does not work========================= Local $oWord = _Word_Create() ;$openFile = FileOpen($file, 0); While 1 Local $line = FileReadLine(_Word_DocOpen($oWord, $file, Default, Default, True)) If @error = -1 Then ExitLoop ;lookForCreditCardNumbers($line) MsgBox(0,0, $line) WEnd FileClose($openFile) ;============================================== part that does not work========================== EndIf EndFunc Func readTxtFile($fileToOpen) $openFile = FileOpen($fileToOpen, 0); open file for reading and assing it to the openFile variable While 1 Local $line = FileReadLine($openFile) If @error = -1 Then ExitLoop lookForCreditCardNumbers($line) WEnd FileClose($openFile) EndFunc Func lookForCreditCardNumbers($evaluateString) $aResult = StringRegExp($evaluateString, '[4|5|3|6][0-9]{15}|[4|5|3|6][0-9]{3}[-| ][0-9]{4}[-| ][0-9]{4}[-| ][0-9]{4}', $STR_REGEXPARRAYMATCH) If Not @error Then Local $newString1 = StringReplace($aResult[0], ' ', '') ;remove spaces Local $newString2 = StringReplace($newString1, '-', '') ;remove dashes Local $bool = _LuhnValidate($newString2) ; Check possible CC number against the Luhn algorithm If $bool = 'True' Then Local $piiCSV = FileOpen($pii, 1) ;open text file for appending/writing, 1 FileWriteLine($piiCSV, $filePath & ', ' & $newString2) FileClose($piiCSV) EndIf EndIf EndFunc