Extract text from last line in log file using vbscript - regex

I have a log file formatted as such:
AssetTag USERNAME Date Time Local
abc123456 Sam 10/15/2015 8:22:14am Local
abc87363 Joe 10/15/2015 8:55:59am Local
I need to extract the USERNAME from the last line of the log file using a batch file. IE: Extract 'Joe' from the last line.
I am thinking some sort regex to find the first space and select the text between the first space and the next space...that should be 'Joe'...
I am using this to extract the last line:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\logs\UserAudit.log", ForReading)
Do Until objFile.AtEndOfStream
strNextLine = objFile.ReadLine
If Len(strNextLine) > 0 Then
strLine = strNextLine
End If
Loop
objFile.Close
Wscript.Echo strLine
EDIT: it is actually 2 tabs that separate the assettag and the username and 1 tab that separate the username and the date

I figured it out with a little more google...
What the below script does..
1) Prompt for asset tag
2) reads last line from log file, extracts username
3)looks up username in AD to find the Staff Name
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
strAsset= INPUTBOX("Please enter the Asset Tag:")
strLog = "\\" & strAsset & "\C$\Logs\UserAudit.log"
'Set objFile = objFSO.OpenTextFile("C:\logs\UserAudit.log", ForReading)
Set objFile = objFSO.OpenTextFile(strLog, ForReading)
Do Until objFile.AtEndOfStream
strNextLine = objFile.ReadLine
If Len(strNextLine) > 0 Then
strLine = strNextLine
End If
Loop
objFile.Close
intStart = InStr(strLine, " ")
If intStart <> 0 Then
intStart = intStart + 2
strText = Mid(strLine, intStart, 250)
For i = 1 to Len(strText)
If Mid(strText, i, 1) = " " Then
Exit For
Else
strData = strData & Mid(strText, i, 1)
End If
Next
End If
'Username from Log file
Wscript.Echo strData
'Lookup Account for Staff Name
SET objSystemInfo = CREATEOBJECT("ADSystemInfo")
strDomain = objSystemInfo.DomainShortName
strUser = strData
wscript.echo GetUserDN(strUser,strDomain)
strAD = GetUserDN(strUser,strDomain)
intStart = InStr(strAD, "CN=")
If intStart <> 0 Then
intStart = intStart + 3
strText = Mid(strAD, intStart, 250)
For i = 1 to Len(strText)
If Mid(strText, i, 3) = ",OU" Then
Exit For
Else
strName = strName & Mid(strText, i, 1)
End If
Next
End If
wScript.echo strName
FUNCTION GetUserDN(BYVAL strUserName,BYVAL strDomain)
SET objTrans = CREATEOBJECT("NameTranslate")
objTrans.Init 1, strDomain
objTrans.SET 3, strDomain & "\" & strUserName
strUserDN = objTrans.GET(1)
GetUserDN = strUserDN
END FUNCTION
'Cleanup
intStart=""
strUser=""
strDomain=""
strName=""
strAD=""
strText=""
strLine=""
strNextLine=""

Related

How to replace double quotes to a space in VBScript?

I need open the CSV file, replace the double quotes with space and save the new file with txt extension.
I have tried this VBScript code but the first file Output_D1.txt is empty, the Output_D2.txt file contains rows of the Output_D1.csv, the Output_D3.txt file contains rows of the Output_D2.csv... etc.
How to do resolve this ?
nArr = Array("D1", "D2", "D3", "D4", "D5", "D6")
Set reP = new RegExp
reP.Pattern = "\"""
For I = 0 To UBound(nArr)
InFilename = "Output_" & nArr(I) & ".csv"
Set FILE1 = CreateObject("scripting.FileSystemObject")
Set infile = FILE1.OpenTextFile(InFileName, 1, False)
strg = reP.Replace(strg, " ")
InFilenameNew = "Output_" & nArr(I) & ".txt"
Set Outfile = File1.CreateTextFile(inFileNameNew, 1, False)
Outfile.Write(strg)
strg = infile.ReadAll
infile.Close
Next
Try this:
You need to set the RegExp global option to replace all occurences of quotes
You need the full path to the CSV files (see rootFolder for a hard-coded example)
ReadAll is used in the wrong place (it needed to be before the RegExp replace!)
Option Explicit
dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
dim rootFolder : rootFolder = "C:\Temp\"
dim nArr : nArr = Array("D1", "D2", "D3", "D4", "D5", "D6")
dim i, inFilename, inFilenameNew, infile, outfile, filecontent
Const ForReading = 1, ForWriting = 2
dim reP : Set reP = new RegExp
reP.Global = true
reP.Pattern = "\"""
For i = 0 To UBound(nArr)
inFilename = rootFolder & "Output_" & nArr(i) & ".csv"
inFilenameNew = rootFolder & "Output_" & nArr(i) & ".txt"
if (fso.FileExists(inFilename)) Then
Set infile = fso.OpenTextFile(InFileName, ForReading)
filecontent = infile.ReadAll
filecontent = reP.Replace(filecontent, " ")
infile.Close
Set infile = Nothing
Set outfile = fso.CreateTextFile(inFileNameNew, True)
outfile.Write(filecontent)
outfile.Close
Set outfile = Nothing
End If
Next
Set reP = Nothing
Set fso = Nothing

Extract all lines of a file between 2 delimiters without them in VBScript Regex

I try to Extract all lines of a file between 2 strings in another file and without these delimiters.
Example:
[General]
Description=Description
[extractSection]
First Line extracted. It is not an ini section
Last Line extracted
[OthersSection]
blablabla
It seems to work with this script. One of my first vbs.
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "E:\Temp\Test.txt"
strTemp = "E:\Temp\Temp.txt"
If objFS.FileExists(strTemp) Then objFS.DeleteFile(strTemp)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If isReading = True Then
If instr(strline,"[") Then
Set objOutFile = objFS.CreateTextFile(strTemp, True)
objOutFile.Write(strLine1)
objOutFile.Close
Exit Do
Else
strline1 = strline1 & strline & vbNewLine
End If
Else
If instr(LCase(strline),"[extractsection]") Then
isReading = True
End If
End If
Loop
objFile.Close
But it seems not very optimized, I have files up to 8Mb.
I would like to try the same thing using Regex. I never used, I have to learn.
I have this as beginning: \[extractsection\]([\s\S]*?)\[[\s\S]
But I would like without the delimiters.
Thank you Wiktor. It seems it is OK with (?<=\[extractSection\]\n)(.*(?:\n(?!\[).*)*) Just let me know what is best (Ram | speed) vs my ReadLine script on top, please
You can give a try for this vbscript without a Regex :
Option Explicit
Dim strFile,strTemp,Full_String,First_Delimiter,Second_Delimiter,Extracted_Data
strFile = "E:\Temp\Test.txt"
strTemp = "E:\Temp\Temp.txt"
Full_String = ReadFileText(strFile)
First_Delimiter = "[extractSection]"
Second_Delimiter = "[OthersSection]"
Extracted_Data = String_Between(Full_String,First_Delimiter,Second_Delimiter)
wscript.echo Extracted_Data
Write2File Extracted_Data,strTemp
'************************************************************************************************
Function String_Between(ByVal Full_String, ByVal First_Delimiter, ByVal Second_Delimiter)
Dim Pos,Pos2
Pos = InStr(Full_String, First_Delimiter)
Pos2 = InStr(Full_String, Second_Delimiter)
If Pos = 0 Or Pos2 = 0 Then
String_Between = "Missing Delimiter"
Exit Function
End If
String_Between = Mid(Full_String, Pos + Len(First_Delimiter), Pos2 - (Pos + Len(First_Delimiter)))
End Function
'***********************************************************************************************
Function ReadFileText(sFile)
Dim objFSO,oTS,sText
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(sFile) Then
MsgBox "CRITICAL ERROR " & VbCrLF & "The File "& DblQuote(sFile) &_
" dosen't exists !",VbCritical,"CRITICAL ERROR"
Wscript.Quit
Else
Set oTS = objFSO.OpenTextFile(sFile)
sText = oTS.ReadAll
oTS.close
set oTS = nothing
Set objFSO = nothing
ReadFileText = sText
End if
End Function
'*********************************************************************************************
Sub Write2File(strText,OutputFile)
Dim fs,ts
Const ForWriting = 2
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(OutputFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'*********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
And this one with RegEx
Option Explicit
Dim strFile,strTemp,Full_String,First_Delimiter,Second_Delimiter,Extracted_Data
strFile = "E:\Temp\Test.txt"
strTemp = "E:\Temp\Temp.txt"
Full_String = ReadFileText(strFile)
First_Delimiter = "[extractSection]"
Second_Delimiter = "[OthersSection]"
Extracted_Data = ExtractData(Full_String,First_Delimiter,Second_Delimiter)
wscript.echo Extracted_Data
Write2File Extracted_Data,strTemp
'***********************************************************************************************
Function ExtractData(Full_String,Start_Delim,End_Delim)
Dim fso,f,r,Matches,Contents,Data
Start_Delim = Replace(Start_Delim,"[","\[")
Start_Delim = Replace(Start_Delim,"]","\]")
End_Delim = Replace(End_Delim,"[","\[")
End_Delim = Replace(End_Delim,"]","\]")
Set r=new regexp
r.pattern = "(?:^|(?:\r\n))(:?"& Start_Delim &"\r\n)([\s\S]*?)(?:\r\n)(?:"& End_Delim &")"
Set Matches = r.Execute(Full_String)
If Matches.Count > 0 Then Data = Matches(0).SubMatches(1)
ExtractData = Data
End Function
'***********************************************************************************************
Function ReadFileText(sFile)
Dim objFSO,oTS,sText
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(sFile) Then
MsgBox "CRITICAL ERROR " & VbCrLF & "The File "& DblQuote(sFile) &_
" dosen't exists !",VbCritical,"CRITICAL ERROR"
Wscript.Quit
Else
Set oTS = objFSO.OpenTextFile(sFile)
sText = oTS.ReadAll
oTS.close
set oTS = nothing
Set objFSO = nothing
ReadFileText = sText
End if
End Function
'*********************************************************************************************
Sub Write2File(strText,OutputFile)
Dim fs,ts
Const ForWriting = 2
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(OutputFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'*********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************

vb script if statement

I want to edit a file with VB if the word that must to be in file isn't exist.
when execute this file, I want if condition was true do nothing but all file content was erase.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading)
strText = objFile.ReadAll
objFile.Close
strSearchFor = "this word must to exist"
If InStr(1, strText, strSearchFor) > 0 then
'do nothing
else
strNewText = Replace(strText,"this word must to delete","this word must to exist" )
End If
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForWriting)
objFile.WriteLine strNewText
objFile.Close
that becouse strNewText will be null when your condition true. and still replace the strText with your empty strNewText.
Keep your works in side the if(). so it will solve the Problem.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading)
strText = objFile.ReadAll
objFile.Close
strSearchFor = "this word must to exist"
If InStr(1, strText, strSearchFor) > 0 then
'do nothing
else
strNewText = Replace(strText,"this word must to delete","this word must to exist" )
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForWriting)
objFile.WriteLine strNewText
objFile.Close
End If

Find and Replace string in a .txt file with VBscript

I am trying to figure out how to use vbscript to:
1 - open a .csv file as a .txt file
2 - search for a certain string of text that is located randomly throughout the text
3 - replace that string with a different string.
I have found an article that helped me learn how to replace an entire line in a .txt document, but so far have had no luck finding anything about replacing just certain characters within the line.
Thanks!
Here is the code I am using currently:
Const ForReading = 1
Const ForWriting = 2
'Setting up our objects and focusing on the text file.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\Documents\Script Practice\TextFiles-2-4-15-Folder\ReadandWrite\Textlook.txt", ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If strLine = "Myer" Then
strLine = "Mike"
End If
strContents = strContents & strLine & vbCrLf
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("C:\Users\Documents\Script Practice\TextFiles-2-4-15-Folder\ReadandWrite\Textlook.txt", ForWriting)
objFile.Write(strContents)
objFile.Close
The text file it references says:
Ken Myer
Fabrikam
Pilar Ackerman
Wingtip Toys
Jeff Hay
Fabrikam
Ellen Adams
Northwind Traders
Myer
(End of text file). So essentially, I have gotten the code to successfully change the "Myer" that is on its own line to "Mike". What I am having a hard time with is changing the "Myer" in the first line to "Mike". Hopefully this helps clarify things a bit...I'm extremely new at this so not sure of the language I should be using to describe the problem.
Use Replace on the file's content obtained by .ReadAll() and .Write the result back. In code:
Option Explicit
Dim goFS : Set goFS = Createobject("Scripting.FileSystemObject")
Dim goWAU : Set goWAU = WScript.Arguments.Unnamed
WScript.Quit main()
Function main()
main = 1 ' assume error
If 3 = goWAU.Count Then
If goFS.FileExists(goWAU(0)) Then
Dim s : s = goFS.OpenTextFile(goWAU(0)).ReadAll()
If 0 < Instr(s, goWAU(1)) Then
goFS.CreateTextFile(goWAU(0)).Write Replace(s, goWAU(1), goWAU(2))
WScript.Echo "done"
main = 0
Else
WScript.Echo goWAU(1), "not found"
End If
Else
WScript.Echo goWAU(0), "does not exist"
End If
Else
WScript.Echo "need 3 args: fspec, find, replacement"
End If
End Function
output:
copy con 28350055.csv
1,2,3
4,5,6
^Z
cscript 28350055.vbs 28350055.csv 5 4711
done
type 28350055.csv
1,2,3
4,4711,6
cscript 28350055.vbs 28350055.csv 5 4711
5 not found
cscript 28350055.vbs 28350055.cs 5 4711
28350055.cs does not exist
Use that demo to determine what is needed to solve your real world problem.
I'm extremly new too, so i didnt get what the other answer do in the code, but i figured out in the last answer about "Replace" and use in your code for do what you need, and the result is this:
Const ForReading = 1
Const ForWriting = 2
'Setting up our objects and focusing on the text file.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\Documents\Script Practice\TextFiles-2-4-15-Folder\ReadandWrite\Textlook.txt", ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
strLine = Replace(strLine,"Myer","Mike")
' If strLine = "Myer" Then
' strLine = "Mike"
' End If
strContents = strContents & strLine & vbCrLf
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("F:\BIBLIOTECAS\Archivos\TEST.txt", ForWriting)
objFile.Write(strContents)
objFile.Close

How can I select and crop certain characters from a string?

For this code, I am having a problem in using the MID and INSTR functions:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set file = objFSO.OpenTextFile("sample.txt" , ForReading)
Const ForReading = 1
Dim re
Dim controller
Dim action
Set re = new regexp
re.pattern = "(contextPath\s*?[+]\s*?[""][/]\w+?[?]action[=]\w+?[""])"
re.IgnoreCase = True
re.Global = True
Dim line
Do Until file.AtEndOfStream
line = file.ReadLine
For Each m In re.Execute(line)
var = m.Submatches(0)
'I am having a problem with the next two lines:
controller = Mid(var, 1, InStr(var, "contextPath\")) & "[?]action[=]\w+?[""]n"
action = Mid(var, 1, InStr(var, "contextPath\s*?[+]\s*?[""][/]\w+?[?]action[=]")) & """"
Wscript.Echo "controller :" & controller
Wscript.Echo "action: " & action
Next
Loop
With the text file "sample.txt":
contextPath+"/GIACOrderOfPaymentController?action=showORDetails"
contextPath +"/GIACPremDepositController?action=showPremDep"
contextPath+ "/GIACCommPaytsController?action=showCommPayts"
(Notice the spaces beside the plus(+) sign)
How can I make the output look like this:
controller: GIACOrderOfPaymentController
controller: GIACPremDepositController
controller: GIACCommPaytsController
action: showORDetails
action: showPremDep
action: showCommPayts
Instead of capturing the full line, capture the needed data
Option Explicit
Const ForReading = 1
Dim re
Set re = New RegExp
With re
.Pattern = "contextPath\s*\+\s*\""/(\w+)\?action=(\w+)\"""
.IgnoreCase = True
.Global = True
End With
Dim controllers, actions
Set controllers = CreateObject("Scripting.Dictionary")
Set actions = CreateObject("Scripting.Dictionary")
Dim file
Set file = CreateObject("Scripting.FileSystemObject").OpenTextFile("sample.txt" , ForReading)
Dim line, m
Do Until file.AtEndOfStream
line = file.ReadLine
For Each m In re.Execute(line)
controllers.Add "K" & controllers.Count, m.Submatches(0)
actions.Add "K" & actions.Count, m.Submatches(1)
Next
Loop
Dim item
For Each item in controllers.Items()
WScript.Echo "controller: " & item
Next
WScript.Echo ""
For Each item in actions.Items()
WScript.Echo "action: " & item
Next