Replacing text function value input in txt file not work - vbscript

This is my expiration.txt file :
foo1; 2020-03-01 13:33;
foo2; 2020-02-01 08:45;
foo3; 2020-01-01 11:30;
I need open the expiration.txt file and replace the all date value from:
2020-03-01 13:33 to 2020-03-01
2020-02-01 08:45 to 2020-02-01
2020-01-01 11:30 to 2020-01-01
I have tried this code without success, because the replace not working.
Const ForReading = 1
Const ForWriting = 2
' create object
set oFSO = CreateObject("Scripting.FileSystemObject")
' open the input file
set oInFile = oFSO.OpenTextFile("expiration.txt", 1)
str_input = ""
' for each line in the input file
do while not oInFile.AtEndOfStream
' read the line
str_input = trim(oInFile.ReadLine())
Wscript.echo str_input
' if date found then exit the loop
if isDate(str_input) then
WScript.echo "Date in file found: '" & str_input & "'"
strNewText = Replace(str_input, left(str_input, 10))
Set objFile = oFSO.OpenTextFile("expiration.txt", 2)
objFile.WriteLine strNewText
WScript.echo "Date in file found: '" & strNewText & "'"
exit do
end if
loop
' close the input file
oInFile.close
' release object from memory
set oFSO = nothing
How to do resolve this ?

Using regular expression
Const ForReading = 1
Const ForWriting = 2
' create object
Set oFSO = CreateObject("Scripting.FileSystemObject")
str_input = ""
' open the input file
Set oInFile = oFSO.OpenTextFile("expiration.txt", 1)
' read the file contents
str_input = oInFile.ReadAll()
' close the input file
oInFile.Close
' use regular expression to find and replace text
Set oRegEx = CreateObject("VBScript.RegExp")
With oRegEx
.Multiline = True
.Global = True
.Pattern = "(\d+)-(\d+)-(\d+)\s(\d+):(\d+);" 'will match entire date including ;
End With
str_input = oRegEx.Replace(str_input, "$1-$2-$3;")
' open the input file to overwrite
Set oInFile = oFSO.OpenTextFile("expiration.txt", 2)
oInFile.Write str_input
' close the input file
oInFile.Close
' release object from memory
set oFSO = nothing

Related

I want to search for the particular word and then after that word on each line i want to add ; in the start

Using below code I was able to add ; in the start of each line but the I want to add ; after a particular word is found e.g. [Abc]. How to do this using VBScript?
Const ForReading=1
Const ForWriting=2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set f = objFSO.OpenTextFile("D:\sam.txt", ForReading)
Do Until f.AtEndOfStream
strText = f.ReadLine
If Len(strText) = 0 Then
blnFound = True
MsgBox "blank line found"
strText = vbNewLine & strText
strContents = strContents & strText & vbCrlf
Else
strText = ";" & strText
strContents = strContents & strText & vbCrlf
End If
Loop
f.Close
Set f = objFSO.OpenTextFile("D:\sam.txt", Forwriting)
f.WriteLine strContents
f.Close
Sam.txt is containing some lines, e.g.
Hi, need help
This is a sample text file
[Abc]
How are you
Hope you are doing well!
So I want the output sam.txt file should have below data inside it:
Hi, need help
This is a sample text file
[Abc]
;How are you
;Hope you are doing well!
So, basically, you have an INI-style file and want the entries in a particular section commented. That can be achieved like this:
filename = "D:\sam.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
txt = Split(fso.OpenTextFile(filename).ReadAll, vbNewLine)
disable = False
For i = 0 To UBound(txt)
If Left(txt(i), 1) = "[" Then
If txt(i) = "[Abc]" Then
disable = True
Else
disable = False
End If
End If
If disable Then txt(i) = ";" & txt(i)
Next
fso.OpenTextFile(filename, 2).Write Join(txt, vbNewLine)
Try this
Option Explicit
Dim FSO ' Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim ReadTxtFile, WriteTxtFile ' Object
Dim TextLine, TextLineToWrite ' String
Dim AddStr' bool
' Open both text file in the same time
Set ReadTextFile = FSO.OpenTextFile("Sam.txt", 1) ' Open file to read
Set WriteTextFile = FSO.OpenTextFile("Sam_new.txt", 2, True) ' Open file to write
' Do read file as normal but add a switch
' Write original text line to text file while switch is disabled
' Add str to the text line and write once switch is trigger
AddStr = False ' Add str disabled
Do Until ReadTextFile.AtEndOfStream ' Start Read
Textline = ReadTextFile.Readline
If AddStr = True Then ' If add str enabled
TextLineToWrite = ";" & Textline ' Add string
Else ' if add str disabled
TextLineToWrite = Textline ' write original line
End If
If Trim(Textline) = "[ABC]" Then ' If indicator read
AddStr = True ' add str write
End if
WriteTextFile.WriteLine TextLineToWrite ' Write file when each line is read
Loop
ReadTextFile.Close
WriteTextFile.Close
msgbox "Done"

VBscript - Hot to Write to a specific blank line?

I need to insert a strText to line 14 in a template.txt file. Line 14 will always be blank before writing (sort of like appending I guess).
What I really need is to copy line 21 to line 14. Not sure what is the easier method to achieve this?
Here is what I have so far but not working. Below code is the template.txt.
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
DIM Infile : Infile = "C:\template.txt"
Set tempFile = objFSO.OpenTextFile (Infile)
strText = tempFile.ReadAll
tempFile.Close
strNewText = Replace(strText, "","Channel_LandWaterMask = 3.0")
Set tempFile = objFSO.OpenTextFile (Infile, 2)
tempfile.Writeline 14, strNewText ‘(How would I write this???)
tempFile.Close
Here is the template.txt:
; Resample INF script for
; Section_YY XX_ZZZZ
[Source]
Type = MultiSource
NumberOfSources = 2
[Source1]
Type = GeoTIFF
Layer = Imagery
SourceDir = "S:\XX\Section_YY\Images"
SourceFile = "XX_ZZZZ_CC.tif"
Variation = DAY
[Source2]
Type = GeoTIFF
Layer = Imagery
SourceDir = "S:\XX\Section_YY\Images"
SourceFile = "XX_ZZZZ_LM.tif"
Variation = Night
Channel_LandWaterMask = 3.0
[Source3]
Type = GeoTIFF
Layer = None
SourceDir = "S:\XX\Section_YY\Images"
SourceFile = "XX_ZZZZ_WM.tif"
SamplingMethod = Gaussian
[Destination]
DestDir = "S:\2_Output\Section_YY"
DestBaseFileName = "XX_ZZZZ"
DestFileType = BGL
LOD = Auto
UseSourceDimensions = 1
CompressionQuality = 85
Take a look at the below example:
sContent = ReadTextFile("C:\template.txt", 0)
aContent = Split(sContent, vbCrLf)
aContent(13) = aContent(20) & vbCrLf & aContent(13)
sContent = Join(aContent, vbCrLf)
WriteTextFile sContent, "C:\template.txt", 0
Function ReadTextFile(sPath, lFormat)
' lFormat -2 - System default, -1 - Unicode, 0 - ASCII
With CreateObject("Scripting.FileSystemObject").OpenTextFile(sPath, 1, False, lFormat)
ReadTextFile = ""
If Not .AtEndOfStream Then ReadTextFile = .ReadAll
.Close
End With
End Function
Sub WriteTextFile(sContent, sPath, lFormat)
' lFormat -2 - System default, -1 - Unicode, 0 - ASCII
With CreateObject("Scripting.FileSystemObject").OpenTextFile(sPath, 2, True, lFormat)
.Write sContent
.Close
End With
End Sub
Note that it inserts the content of the line 21 before the line 14, thus preserving newline, since the content of the line 14 are newline chars. If you want just replace, then use aContent(13) = aContent(20) instead of aContent(13) = aContent(20) & vbCrLf & aContent(13).
Do Until Inp.AtEndOfStream
Count=Count + 1
Line=Inp.readline
If Count = 14 then
outp.writeline "My line 14"
Else
outp.writeline Line
End If
Loop
Is the pattern for your type of problem. Read a line, make a decision, write something.

Append text to text file if it already exists

I have a script which is working, to replace some characters in a fixed width file (starting from row 2 onward).
What want to avoid overwriting the target file if it already exists. Instead, if it exists, to append the rows (from row 2 onwards of the source file) to the end of the target file. I am struggling to find a thread with a proper suggestion. This is the current code:
Dim objFSO
dim objFile
dim thisLine
Set objFSO = CreateObject("Scripting.FileSystemObject")
If (objFSO.FileExists("C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat")) Then
Set objFile = objFSO.GetFile("C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat")
Else
WScript.Quit()
End If
If objFile.Size > 0 Then 'make sure the input file is not empty
Set inputFile = objFSO.OpenTextFile("C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat", 1) 'Replace the filename here
set outputFile = objFSO.CreateTextFile("C:\Users\Dimitar\Desktop\BPSDRC\PAYIMP.dat", TRUE) 'replace it with output filename
' first line - leave it as it is
thisLine = inputFile.ReadLine
newLine = thisLine
outputFile.WriteLine newLine
'all remaining lines - read them and replace the middle part with 18 zeroes
do while not inputFile.AtEndOfStream
thisLine = inputFile.ReadLine ' Read an entire line into a string.
'the zeroes are to fix issue N1 (payment in other amt)
'the CDF are to fix issue N2 (payment in local amt)
newLine = mid(thisLine,1,47) & "000000000000000000" & mid(thisLine,66,121) & "CDF" & mid(thisLine,190)
outputFile.WriteLine newLine
loop
inputFile.Close
outputFile.Close
objFSO.DeleteFile "C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat"
end if
Open the file for appending
Option Explicit
Const ForReading = 1, ForAppending = 8
Dim inputFileName, outputFileName
inputFileName = "C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat"
outputFileName = "C:\Users\Dimitar\Desktop\BPSDRC\PAYIMP.dat"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists( inputFileName ) Then
WScript.Quit
End If
If fso.GetFile( inputFileName ).Size < 1 Then
WScript.Quit
End If
Dim newFile, inputFile, outputFile
newFile = Not fso.FileExists( outputFileName )
Set inputFile = fso.OpenTextFile( inputFileName, ForReading )
Set outputFile = fso.OpenTextFile( outputFileName, ForAppending, True )
Dim lineBuffer
lineBuffer = inputFile.ReadLine()
If newFile Then
outputFile.WriteLine lineBuffer
End If
Do While Not inputFile.AtEndOfStream
lineBuffer = inputFile.ReadLine
lineBuffer = mid(lineBuffer,1,47) & "000000000000000000" & mid(lineBuffer,66,121) & "CDF" & mid(lineBuffer,190)
outputFile.WriteLine lineBuffer
Loop
inputFile.Close
outputFile.Close
fso.DeleteFile inputFileName

Read integer from text file and replace with different integer

I'm working with the below code
Dim objFSO, objFile, maxRetry, numRetries, newRetries
CONST ForReading = 1
CONST ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(MICacheFilename(), ForReading)
maxRetry = CInt(MIGetTaskParam("maxRetry"))
strText = objFile.ReadAll
Set numRetries = CInt(objFile.ReadLine)
IF numRetries >= maxRetry THEN
MISetTaskParam "RerunTask", "False"
strLine = Replace(strLine,numRetries ,0)
Else
MISetTaskParam "RerunTask", "True"
Set newRetries = numRetries + 1
strLine = Replace(strLine,numRetries ,newRetries)
END IF
MICacheFilename() and MIGetTaskParam are passed into the script as a file path and an integer. My goal is to compare the max value passed in to the value in the file and set MISetTaskParam based on the comparison. I'm very new to VB and this seems like it shoudl be easier than I'm finding. The input file is a text file that only contains an integer.
While my first instinct would be to stay in a loop this script is only called periodically and needs to be an IF.
I am currently getting the error object requried with set numRetries = CInt(objFile.ReadLine)
mhopkins321, you say:
I am currently getting the error object requried with set numRetries =
CInt(objFile.ReadLine)
That is because the Set keyword is used only for setting a variable that holds an instance of an object. In your case, the purpose numRetries is to hold an integer.
So, try this instead:
numRetries = CInt(objFile.ReadLine)
I found a few other issues with your script. Here is my edited version with some comments:
Option Explicit ' Checks that you have declared all variables
Dim objFSO, objFile, maxRetry, numRetries, newRetries
Dim strText, strLine ' declare these also
CONST ForReading = 1
CONST ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(MICacheFilename(), ForReading)
maxRetry = CInt(MIGetTaskParam("maxRetry"))
' strText = objFile.ReadAll ' Not needed
numRetries = CInt(objFile.ReadLine) ' just read the one line in the file
WScript.Echo "numRetries = [" & numRetries & "]"
IF numRetries >= maxRetry THEN
MISetTaskParam "RerunTask", "False"
strLine = Replace(strLine,numRetries ,0) ' does nothing, 'strline' is empty
Else
MISetTaskParam "RerunTask", "True"
newRetries = numRetries + 1
strLine = Replace(strLine,numRetries ,newRetries) ' does nothing, 'strline' is empty
END IF
WScript.Echo "strLine = [" & strLine & "]"
' Dummy Function.
Function MICacheFilename()
MICacheFilename = "retries.txt"
End Function
' Dummy Function.
Function MIGetTaskParam(key)
MIGetTaskParam = 13
End Function
' Dummy Sub.
Sub MISetTaskParam(arg1, arg2)
End Sub

.vbs Help me loop this through a directory

I have written a script that works. What it does now is it looks through a directory to a given file and returns what is on the second row fourth tab (RXC193) and renames the file to that of which it found from a file like this:
#Program #RxBIN #RXPCN #RxGroup #MemberID #WebsiteE #WebsiteS #VerticalLogo #TextLogo
RXCUT 013824 RXCUT RXC193 RXC5FHXF9 www.rxcut.com/HBG www.rxcut.com/HBG/es P:\RxCut\In Design Implementation\RXC193
What I need this script to be able to do is loop through the directory and rename all files by this RXC#####. Here is the script:
Call TwoDimensionArrayTest
Sub TwoDimensionArrayTest
' Version 1.0
' Writtem by Krystian Kara
' Dated 25-Jan-2009
Dim fso
Dim oFile
Dim arrline
Dim arrItem
Dim objFolder
Dim i
Dim arrMain()
Dim sFileLocation, strResults
Const forReading = 1
' The file contains on each line:
' Text1 (tab) Text2 (tab) Text3 (tab) Text4
' Text5 (tab) Text6 (tab) Text7 (tab) Text8
'etc etc
Set fso = CreateObject("Scripting.FileSystemObject")
sFileLocation = "file 2.txt"
Set oFile = fso.OpenTextFile(sFileLocation, forReading, False)
Do While oFile.AtEndOfStream <> True
strResults = oFile.ReadAll
Loop
' Close the file
oFile.Close
' Release the object from memory
Set oFile = Nothing
' Return the contents of the file if not Empty
If Trim(strResults) <> "" Then
' Create an Array of the Text File
arrline = Split(strResults, vbNewLine)
End If
For i = 0 To UBound(arrline)
If arrline(i) = "" Then
' checks for a blank line at the end of stream
Exit For
End If
ReDim Preserve arrMain(i)
arrMain(i) = Split(arrline(i), vbTab)
Next
fso.MoveFile "file 2.txt", arrMain(1)(3) & ".txt"
End Sub ' TwoDimensionArrayTest
Thanks in advance,
Joe
One approach is to parameterize the file name in your sub-procedure so it can be called multiple times for different files, like this:
Sub TwoDimensionArrayTest(fileName) 'you may want a more descriptive name
' ...
sFileLocation = fileName
' ...
End Sub
Then, write a loop that goes through your directory, calling your sub each time around:
Dim fso, folder
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("Your Folder Name")
For Each file In folder.Files
TwoDimensionArrayTest file.Path
Next
Here is the Final Error free code! Finally have it searching through my directory of Tab-delimited.txt files and grabbing from the second row third tab (group number) then renaming the files to its corrisponding group number! YAY!
heres final error free code!:
Call TwoDimensionArrayTest
Sub TwoDimensionArrayTest
Dim fso
Dim oFile
Dim arrline
Dim arrItem
Dim i
Dim arrMain()
Dim sFileLocation, strResults
Const forReading = 1
strFolder = "C:\Documents and Settings\jmituzas.NMCLLC\Desktop\desktop2\New Folder (2)\datafiles"
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFile In objFSO.GetFolder(strFolder).Files
If Right(LCase(objFile.Name), 4) = LCase(".txt") Then
' The file contains on each line:
' Text1 (tab) Text2 (tab) Text3 (tab) Text4
' Text5 (tab) Text6 (tab) Text7 (tab) Text8
'etc etc
Set fso = CreateObject("Scripting.FileSystemObject")
sFileLocation = objFile.Name
Set oFile = fso.OpenTextFile(objFile.Name, forReading, False)
Do While oFile.AtEndOfStream <> True
strResults = oFile.ReadAll
Loop
' Close the file
oFile.Close
' Release the object from memory
Set oFile = Nothing
' Return the contents of the file if not Empty
If Trim(strResults) <> "" Then
' Create an Array of the Text File
arrline = Split(strResults, vbNewLine)
End If
For i = 0 To UBound(arrline)
If arrline(i) = "" Then
' checks for a blank line at the end of stream
Exit For
End If
ReDim Preserve arrMain(i)
arrMain(i) = Split(arrline(i), vbTab)
Next
fso.MoveFile sFileLocation, arrMain(1)(3) & ".txt"
End If
Next
End Sub ' TwoDimensionArrayTest

Resources