Sandhya

read the string inbetween 2 strings

20 posts in this topic

#1 ·  Posted (edited)

I need to read the value, normally a number, inbetween 2 strings from a text file. I tried the following code, but not returned result. please tell me a way.

Local $file = "D:\AutoIT\CMP.TXT"
Run ("notepad.exe " & $file)
WinWaitActive ("CMP.TXT")
Local $sTemp = FileReadLine($file)
Local $aArray = _StringBetween($sTemp, "All selected attributes", "Long identifier")
_ArrayDisplay($aArray)

Edited by Sandhya

Share this post


Link to post
Share on other sites



What has Notepad doing here? And what is in the file exactly?


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

i need to find the value between two string in a log file.

Share this post


Link to post
Share on other sites

So leave Notepad alone and go ahead. If anything fails, post a short reproducer so that somebody can help.


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

@Sandhya , As jchd said, you don't need to open notepad for this. First of all read all lines of the text file to an array. That's what you did in your script. And then loop through each element in your array. Check for your number in each element. You can use regular expression for this. 

 


My Contributions

UDF Link Viewer   --- A tool to visit the links of some most important UDFs 

 Includer_2  ----- A tool to type the #include statement automatically 

 Digits To Date  ----- date from 3 integer values

PrintList ----- prints arrays into console for testing.

 Alert  ------ An alternative for MsgBox 

 MousePosition ------- A simple tooltip display of mouse position

GRM Helper -------- A littile tool to help writing code with GUIRegisterMsg function

Access_UDF  -------- An UDF for working with access database files. (.*accdb only)

 

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

You mean like the below one?

Local $file = "D:\AutoIT\CMP.TXT"
Local $sTemp = FileReadLine($file)
Local $aArray = _StringBetween($sTemp, "All selected attributes", "Long identifier")
_ArrayDisplay($aArray)

this will not even open the file right?

i tried like this also. but didnt work.

Local $file = "D:\AutoIT\CMP.TXT"

Local $start = "All selected attributes"
Local $end = "Long identifier"
Local $hFileOpen = FileOpen($file, $FO_READ)
WinWaitActive ("CDM_CMP.TXT")
Local $sTemp = FileReadLine($hFileOpen)
Local $aArray = _StringBetween($sTemp, $start, $end)
_ArrayDisplay($aArray)

Edited by Sandhya

Share this post


Link to post
Share on other sites

Take out the WinWaitActive. This works just fine for me (saved the text file to my desktop):

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

Local $file = @DesktopDir & "\CMP.TXT"
Local $start = "All selected attributes"
Local $end = "Long identifier"
Local $hFileOpen = FileOpen($file, $FO_READ)
Local $sTemp = FileReadLine($hFileOpen)
Local $aArray = _StringBetween($sTemp, $start, $end)
_ArrayDisplay($aArray)
FileClose($file)

 


When you're dead, you don't know you're dead - it's only difficult for those that know you. It's the same way when you're stupid...

My Scripts: SCCM UDFInclude Source with Compiled Script, Windows Firewall UDF

Share this post


Link to post
Share on other sites

@Sandhya when you post code please wrap inside a code block.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

Try something like this?

#Include <File.au3>
#Include <String.au3>
#Include <Array.au3>

$vFile = @ScriptDir & "\cmp.txt"

Local $aFile
Local $aFinal[0]

_FileReadToArray($vFile, $aFile)

For $i = 1 to $aFile[0]
    $sTemp = _StringBetween($aFile[$i], "All selected attributes", "Long identifier")
    If $sTemp <> 0 Then _ArrayAdd($aFinal, $sTemp[0])
Next

_ArrayDisplay($aFinal)

And I am not sure but it may be faster with RegEx

#Include <File.au3>
#Include <String.au3>
#Include <Array.au3>
#Include <StringConstants.au3>

$vFile = @ScriptDir & "\cmp.txt"

Local $aFile
Local $aFinal[0]

_FileReadToArray($vFile, $aFile)

For $i = 1 to $aFile[0]
    ;$sTemp = _StringBetween($aFile[$i], "All selected attributes", "Long identifier")
    $sTemp = StringRegExp($aFile[$i], "(?i)all selected attributes (.*) long identifier", $STR_REGEXPARRAYMATCH)
    If $sTemp <> 0 Then _ArrayAdd($aFinal, $sTemp)
Next

_ArrayDisplay($aFinal)

And this possibly faster yet.

#Include <File.au3>
#Include <String.au3>
#Include <Array.au3>
#Include <StringConstants.au3>

$vFile = @ScriptDir & "\cmp.txt"

$hFile = FileOpen($vFile)
$sFile = FileRead($hFile)
Local $aFinal[0]

$aFinal = StringRegExp($sFile, "(?i)all selected attributes (.*) long identifier", $STR_REGEXPARRAYGLOBALMATCH)

FileClose($hFile)

_ArrayDisplay($aFinal)

 

String Between.au3

String Between RegEx.au3

String Between RegEx2.au3

cmp.txt

Edited by ViciousXUSMC
1 person likes this

Share this post


Link to post
Share on other sites

You mean like the below one?

Local $file = "D:\AutoIT\CMP.TXT"
Local $sTemp = FileReadLine($file)
Local $aArray = _StringBetween($sTemp, "All selected attributes", "Long identifier")
_ArrayDisplay($aArray)

this will not even open the file right?

 

Function FileReadLine will accept an optional parameter line. But you didn't provided it. So i am assuming that your txt file had only one line text. If it is right, then you can do some error check. I think your variable $sTemp is probably null value . Do one thing. First open the file with FileOpen() function. Then use the file handle instead of file path in FileReadLine function. 


My Contributions

UDF Link Viewer   --- A tool to visit the links of some most important UDFs 

 Includer_2  ----- A tool to type the #include statement automatically 

 Digits To Date  ----- date from 3 integer values

PrintList ----- prints arrays into console for testing.

 Alert  ------ An alternative for MsgBox 

 MousePosition ------- A simple tooltip display of mouse position

GRM Helper -------- A littile tool to help writing code with GUIRegisterMsg function

Access_UDF  -------- An UDF for working with access database files. (.*accdb only)

 

Share this post


Link to post
Share on other sites

If the first and only line of the file is needed then use FileReadLine().

#include <Array.au3>
#include <String.au3>

Local $file = "CMP1.TXT"
If FileExists($file) = 0 Then
    FileWrite($file, "To all selected attributes 26 Long identifier end" & @CRLF & "Next line All selected attributes 522 long identifier to end.")
EndIf

Local $aArray = _StringBetween(FileRead($file), "All selected attributes", "Long identifier", $STR_ENDNOTSTART)

_ArrayDisplay($aArray)
FileDelete($file)

 

Share this post


Link to post
Share on other sites

Thank you all.

Some problem with text file itself. Otherwise the code is perfect.

Share this post


Link to post
Share on other sites

if space and next line are there, will it be able to identify the value? That is what is happening in my case. the below given text are part of the file and I need to find the value "5".

  All selected attributes              5
  Long identifier

Share this post


Link to post
Share on other sites

@Sandhya If the file has more lines, then you need to supply the line number parameter for FileReadLine function. Otherwise it will read the first line. As far as i know your problem, i can tell you that using regular expression will solve your problem easily. If your file has more than one line and you don't know in which line the number resides, then you can read all line to an array and loop through them and check each line with regex.


My Contributions

UDF Link Viewer   --- A tool to visit the links of some most important UDFs 

 Includer_2  ----- A tool to type the #include statement automatically 

 Digits To Date  ----- date from 3 integer values

PrintList ----- prints arrays into console for testing.

 Alert  ------ An alternative for MsgBox 

 MousePosition ------- A simple tooltip display of mouse position

GRM Helper -------- A littile tool to help writing code with GUIRegisterMsg function

Access_UDF  -------- An UDF for working with access database files. (.*accdb only)

 

Share this post


Link to post
Share on other sites

#15 ·  Posted (edited)

Can you post a full example of your text file?  Is the value always a single number?

It will be pretty easy using one of the two RegEx examples I have above once we know exactly what it is your looking at. 

I am no RegEx guy but I came up with this that works given the example you gave.

#Include <File.au3>
#Include <String.au3>
#Include <Array.au3>
#Include <StringConstants.au3>

$vFile = @ScriptDir & "\cmp.txt"

$hFile = FileOpen($vFile)
$sFile = FileRead($hFile)
Local $aFinal[0]

$aFinal = StringRegExp($sFile, "(?i)all selected attributes\s+(\w+)\s", $STR_REGEXPARRAYGLOBALMATCH)

FileClose($hFile)

_ArrayDisplay($aFinal)

 

Edited by ViciousXUSMC

Share this post


Link to post
Share on other sites
$aMatch = stringregexp(stringstripws($sString , 8) , "(?i)allselectedattributes(\d+)longidentifier" , 3)
_ArrayDisplay($aMatch)

 


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

Share this post


Link to post
Share on other sites

If "longidentifier" is on a new line its not going to show up in that search is it? as a @LF or @CRLF is not stripped as whitespace.

Share this post


Link to post
Share on other sites

#18 ·  Posted (edited)

it will

Whitespace includes Chr(9) thru Chr(13) which are HorizontalTab, LineFeed, VerticalTab, FormFeed, and CarriageReturn. Whitespace also includes the null string ( Chr(0) ) and the standard space ( Chr(32) ).

$sString = "All selected attributes              5" & @CRLF & "Long identifier"
;~ $sString = "To all selected attributes 26 Long identifier end" & @CRLF & "Next line All selected attributes 522 long identifier to end."

$aMatch = stringregexp(stringstripws($sString , 8) , "(?i)allselectedattributes(\d+)longidentifier" , 3)

for $sMatch in $aMatch
   msgbox(0, '' , $sMatch)
next

 

Edited by boththose

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

Share this post


Link to post
Share on other sites

#19 ·  Posted (edited)

Well that is good to know, so it puts the entire file on a single line basically as a giant block of text :)

Since the OP said "usually" a number I think that means we may need to take into account for words as well.  I had to make the \w lazy else it was pulling bad results.  This looks good to me other than if your words had a space the space would be stripped as my example file has "test string 2" it will result with "teststring2"

#Include <File.au3>
#Include <String.au3>
#Include <Array.au3>
#Include <StringConstants.au3>

$vFile = @ScriptDir & "\cmp.txt"

$hFile = FileOpen($vFile)
$sFile = FileRead($hFile)
$sFileStrip = StringStripWS($sFile, $STR_STRIPALL)
Local $aFinal[0]

$aFinal = StringRegExp($sFileStrip, "(?i)allselectedattributes(\w+?)longidentifier", $STR_REGEXPARRAYGLOBALMATCH)

FileClose($hFile)

_ArrayDisplay($aFinal)

 

String Between RegEx3.au3

cmp.txt

Edited by ViciousXUSMC

Share this post


Link to post
Share on other sites

#20 ·  Posted (edited)

Thanks a lot guys..

Edited by Sandhya

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