Find and Replace string in a .txt file with VBscript - replace

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

Related

Change Text in Textfile with Search & Replace + Regex | Batchfile

I need to write a .bat/.cmd/.vbs file that changes the text of a text file and I also need regex terms.
I have the following text file as .txt.
"Bild/Print/59/00-Einstiegsbild-neu_59115.jpg" -resize 227.05x227.05%% -rotate -0 -shear 0x0 -crop 2011x1051+104+328 "web\00-Einstiegsbild-neu_59115.jpg"
"Bild/Print/59/01-Zwischenbild-neu_59150.jpg" -resize 100.39x100.39%% -rotate -0 -shear 0x0 -crop 2012x988+0+82 "web\01-Zwischenbild-neu_59150.jpg"
Now I want to do the following regex search and replace:
(1. Replace)
Search: "
Replace: (nothing)
(2. Replace)
Search: .+(?=web)
Replace: (nothing)
Now the text should be:
web\00-Einstiegsbild-neu_59115.jpg
web\01-Zwischenbild-neu_59150.jpg
(3. Replace)
Search: web\\
Replace: E:\K4_XML_Export\tpx_K4toWP_ImageMagick\web\
which should result in:
E:\K4_XML_Export\tpx_K4toWP_ImageMagick\web\00-Einstiegsbild-neu_59115.jpg
E:\K4_XML_Export\tpx_K4toWP_ImageMagick\web\01-Zwischenbild-neu_59150.jpg
Since I have absolutely no idea about batch files I hope you can help me further or share certain approaches or considerations.
Thank you in advance for the feedback and best regards
Noel
What I already tested – I know how to change text like red to blue with:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "E:\imglist_2.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"red")> 0 Then
strLine = Replace(strLine,"red","blue")
End If
WScript.Echo strLine
Loop
cscript /nologo E:\test.vbs > newfile
ren newfile file.txt
I hope this helps... Regular expression can skip a few steps ahead and just grab the string (web...) without needing the redundant steps. Resulting in the desired pattern output.
Please note you'll need to update this version back to your file strFile = "E:\imglist_2.txt"
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim objFS, objFile, PrimaryPath, strFile
PrimaryPath="E:\K4_XML_Export\tpx_K4toWP_ImageMagick"
strFile = "imagelist.txt"
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.OpenTextFile(strFile, ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"web")> 0 Then ImagePath = PrimaryPath & "\" & GetWebImg(strLine)
WScript.Echo ImagePath
Loop
Function GetWebImg(str)
Set RE = CreateObject("VBScript.RegExp")
RE.Global = True
RE.Pattern = "(web[^""]*)"
Set matches = RE.Execute(str)
If matches.count > 0 Then
GetWebImg=matches(0)
End If
End Function

Structure replacement possible complex RegexReplace solution?

I need to run a VBScript that changes the structure of a CSV file. To keep it simple I'm only using 3 data fields but there is a lot more. In a production environment I will have a CSV file with hundreds of lines.
The problem is everything is in double quotes. The end result can sometimes be no quotes or single quotes or sometimes a mix of all three.
I have absolutely no idea how I should approach this and was looking for some guidance. This looks like a job for RegexReplace but because it's mixed I'm not sure how to start this. After the file has been modified I have to right over top of the original file.
CSV Example:
"apple";"12";"xyz"
"somereallylongword";"7687";"theredfox"
Pattern
"%1";%2;'%3'
Desired Result
"apple";12;'xyz'
"somereallylongword";7687;'theredfox'
What I'm trying to achieve is to be able to make a new pattern type.  In my example:
"%1" - I keep the original double quotes.
%2 - Remove the double quotes.
'%3' - Replace the double quotes with single quotes.
Any insight would be greatly appreciated.
You can read the CSV file using ADODB:
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Dim objConnection
Dim objRecordset
Dim sCSVFolder
Dim sCSVFile
Dim sValue
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
sCSVFolder = "C:\CSV_Folder\"
sCSVFile = "your_csv_file.csv"
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sCSVFolder & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
objRecordset.Open "SELECT * FROM " & sCSVFile, _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
Do Until objRecordset.EOF
' Modify and write fields to new text file here
sValue = objRecordset.Fields.Item("FieldName")
objRecordset.MoveNext
Loop
This way you let ADO handle reading the data and removing the double-quotes and you can manipulate the data easily as a Recordset.
Just give a try for this code by replacing the path of your CSV file and tell me how it works on your side ?
Option Explicit
Dim Data
Call ForceCScriptExecution()
Data = ReadFile("C:\Test\Test.csv")
wscript.echo "Before Replacing"
wscript.echo String(50,"-")
wscript.echo Data
wscript.echo String(50,"-")
wscript.echo "After Replacing"
wscript.echo String(50,"-")
wscript.echo Search_Replace(Data)
wscript.echo String(50,"-")
wscript.sleep 20000
'-----------------------------------------------
Function Search_Replace(Data)
Dim oRegExp,strPattern1,strPattern2
Dim strReplace1,strReplace2,strResult1,strResult2
strPattern1 = ";(\x22)(\S+\w+)(\x22);"
strReplace1 = ";$2;"
strPattern2 = "[;]\x22([^\x22]+)\x22"
strReplace2 = ";'$1'"
Set oRegExp = New RegExp
oRegExp.Global = True
oRegExp.IgnoreCase = True
oRegExp.Pattern = strPattern1
strResult1 = oRegExp.Replace(Data,strReplace1)
oRegExp.Pattern = strPattern2
strResult2 = oRegExp.Replace(strResult1,strReplace2)
Search_Replace = strResult2
End Function
'-----------------------------------------------
Function ReadFile(path)
Const ForReading = 1
Dim objFSO,objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(path,ForReading)
ReadFile = objFile.ReadAll
objFile.Close
End Function
'----------------------------------------------
Sub ForceCScriptExecution()
Dim Arg, Str, cmd, Title
Title = "Search and Replace using RegExp by Hackoo 2019"
cmd = "CMD /C Title " & Title &" & color 0A & Mode 80,30 & "
If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then
For Each Arg In WScript.Arguments
If InStr( Arg, " " ) Then Arg = """" & Arg & """"
Str = Str & " " & Arg
Next
CreateObject( "WScript.Shell" ).Run _
cmd & "cscript //nologo """ & _
WScript.ScriptFullName & _
""" " & Str
WScript.Quit
End If
End Sub
'-----------------------------------------------
Edit : Batch Script Code
You can do it easily with a batch script without using Regex :
#echo off
Title Edit CSV File
Set "Input_CSV_File=C:\Test\Test.csv"
Set "OutPut_CSV_File=C:\Test\OutPut_Test.csv"
If Exist "%OutPut_CSV_File%" Del "%OutPut_CSV_File%"
#for /f "tokens=1,2,3 delims=;" %%a in ('Type "%Input_CSV_File%"') Do (
echo "%%~a";%%~b;'%%~c'
echo "%%~a";%%~b;'%%~c'>>"%OutPut_CSV_File%"
)
TimeOut /T 5 /NoBreak>nul
If Exist "%OutPut_CSV_File%" Notepad "%OutPut_CSV_File%" & Exit

Excel VBA - Returning Positions of all Sub-Strings within a String from the Clipboard

I'm trying to find all the positions of the unique keys (followed by two Tab keystrokes) in a string in taken from clipboard, positions with which I then hope to use to insert carriage returns, and then have everything put back into the clipboard again.
First things first; getting the position part to work!
Here is a shortened example of the string:
Initial Approval in First Market or Non-Submitted Closure 090052fb842ef82f 090052fb842f3659 090052fb842ef82e
Here is the non-functional code I have put together so far from researching the problem:
Sub oldRecords()
Dim clipboard As MSForms.DataObject
Dim strContents As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
Set objRegEx = CreateObject("vbscript.regexp")
objRegEx.Pattern = "(090052fb)[0-9A-Za-z]{8}\t\t"
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.MultiLine = True
Start = 1
Do
pos = InStr(Start, strContents, objRegEx.Execute(strContents), vbBinaryCompare)
If pos > 0 Then
Start = pos + Len(objRegEx.Pattern)
WScript.Echo pos
WScript.Echo Mid(strContents, pos, Len(objRegEx.Pattern))
End If
Loop While pos > 0
End Sub
Right now I am getting a Run-time error '450': Wrong number of arguments or invalid property assignment, and I believe the culprit is:
objRegEx.Execute(strContents)
I'm not sure where to go from here, so any help would be fantastic! :)
Edit 1:
Firstly thank you for the interest in my issue!
BrackNicku has provided a simple solution for a problem I evidently thought more complex than it needed to be! Here is the code I finally went with, adding in a few extra bits that I needed on top of the core issue:
Sub oldRecords2()
Dim clipboard As MSForms.DataObject
Dim strContents As String
Dim start As Long, pos As Long
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
Dim objRegEx
Set objRegEx = CreateObject("vbscript.regexp")
objRegEx.Pattern = "(090052fb[0-9A-Za-z]{8})\t\t"
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.MultiLine = True
X1 = 10 ' Line Feed Character
X2 = 13 ' Carriage Return Character
X3 = "Archive Custodain Group"
X4 = "Archive Custodain Group" & Chr(X2)
'======================================================================================================
strContents = Replace(strContents, Chr(X1), "") ' REMOVES LINE FEEDS
strContents = Replace(strContents, X3, X4) ' ADDS CR AFTER TITLE ROW
strContents = objRegEx.Replace(strContents, "$1" & vbNewLine)
'======================================================================================================
clipboard.SetText strContents 'PUT BACK INTO CLIPBOARD
clipboard.PutInClipboard
End Sub
When you run objRegEx.Execute(strContents), it returns a match collection. Then, you are not even using the results as Len(objRegEx.Pattern) returns the length of the pattern and not the match.
It seems you just want to obtain the matches and their indices in the string. Remove all starting from Start = 1 and ending with Loop While pos > 0 and use
Dim ms As Object, m As Object
'...
objRegEx.Pattern = "(090052fb[0-9A-Za-z]{8})\t\t"
'...
Set ms = objRegEx.Execute(strContents)
For Each m In ms
WScript.Echo m.FirstIndex
WScript.Echo m.SubMatches(0)
Next
Tested with
strContents = "Initial Approval in First Market or Non-Submitted Closure" & vbTab & vbTab & "090052fb842ef82f" & vbTab & vbTab & "090052fb842f3659" & vbTab & vbTab & "090052fb842ef82e" & vbTab & vbTab
Result:
59
090052fb842ef82f
77
090052fb842f3659
95
090052fb842ef82e
Note I moved the capturing group around all but tab pattern, (090052fb[0-9A-Za-z]{8})\t\t, feel free to adjust as per your needs.
I'm trying to find all the positions of the unique keys (followed by
two Tab keystrokes) in a string in taken from clipboard, positions
with which I then hope to use to insert carriage returns, and then
have everything put back into the clipboard again.
If you want to insert new lines before each key, then instead of locating the keys and inserting new lines, you could try RegExp.Replace
strContents = objRegEx.Replace(strContents, vbNewLine & "$1")
You have to modify the pattern to include whole key in the group:
objRegEx.Pattern = "(090052fb[0-9A-Za-z]{8})\t\t"
Result:
Initial Approval in First Market or Non-Submitted Closure
090052fb842ef82f
090052fb842f3659
090052fb842ef82e
Full code (with new line after pattern):
Sub oldRecords()
Dim clipboard As MSForms.DataObject
Dim strContents As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
Dim objRegEx
Set objRegEx = CreateObject("vbscript.regexp")
objRegEx.Pattern = "(090052fb[0-9A-Za-z]{8})\t\t"
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.MultiLine = True
strContents = objRegEx.Replace(strContents,"$1" & vbNewLine)
'Put back to clipboard
clipboard.SetText strContents
clipboard.PutInClipboard
End Sub
Using your string example I came into this:
Sub findKeyPositions()
Dim str As String
Dim splitStr() As String
Dim searchStr As String
str = "Initial Approval in First Market or Non-Submitted Closure 090052fb842ef82f 090052fb842f3659 090052fb842ef82e "
splitStr() = Split(Replace(str, "090052fb", ""), " ") 'in your example i did it with 7 spaces and not vbtab
For i = LBound(splitStr) To UBound(splitStr)
searchStr = Trim(splitStr(i))
Debug.Print (InStr(1, str, searchStr, vbTextCompare))
Next i
End Sub
If I understand your post correctly you want to replace the Tabs with CR
If so, then there's no need to find the positions, you could just replace.
Sub replaceTab()
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
clipboard.SetText Replace(clipboard.GetText, vbTab, vbCrLf)
clipboard.PutInClipboard
End Sub

Find and replace with a regular expression in a text file

I am building a jenkins jobs for build comparison. I want to replace double newline (\n\n) in the text file with single new line (\n). After that I want to replace every instance of word "commit" with a newline and commit i.e "\ncommit". I want to use a vbscript for this, anyone can suggest how to do this?
Currently I am using following VBScript:
Const ForReading = 1
Const ForWriting = 2
strName = Wscript.Arguments(0)
strOriginal = Wscript.Arguments(1)
strReplacement = Wscript.Arguments(2)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strName, ForReading)
strText = objFile.ReadAll
objFile.Close
' Replace desired string
Set objRegExp = New RegExp
objRegExp.Global = True
objRegExp.IgnoreCase = False
objRegExp.Pattern = strOriginal
strReplacement = objRegExp.Replace(strText, strReplacement)
Set objFile = objFSO.OpenTextFile(strName, ForWriting)
objFile.Write strReplacement
objFile.Close
The script replaces regex patterns with a normal string, i.e. it replaces double newline with a normal string i.e with string \n. I don't know how to extend this to replace regex with regex.
Regular expressions are overkill for this. Use two string replacements:
strText = objFSO.OpenTextFile(strName, ForReading).ReadAll
strText = Replace(strText, vbLf & vbLf, vbLf)
strText = Replace(strText, "commit", vbLf & "commit")
objFSO.OpenTextFile(strName, ForWriting).Write strText

VBS RegEx Search and Replace

I am attempting to use a vbs script to replace the limit value in a .ini file that contains the following line:
CC_refund_limit=####.##
Unfortunately the ####.## can be any dollar value. I am replacing with a standard:
CC_refund_limit=500.00
I have attempted the following with every variation of \d \d+ enclosed in every bracket known to mankind and have even attempted [0-999] on a test file. The only way I can get this to work has been with the following code and only if the string contains an actual dollar value as written. I have over 1600 instances on as many different servers to replace this on.
Any guidance would be appreciated:
`Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "CC_refund_limit=200.00", "CC_refund_limit=500.00")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForWriting)
objFile.WriteLine strNewText
objFile.Close
`
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForReading)
strText = objFile.ReadAll
objFile.Close
Set r = New Regexp
With r
.pattern = "CC_refund_limit=\d+\.\d+"
.global = true
End with
StrNewText = r.Replace(strText,"CC_refund_limit=500.00")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForWriting)
objFile.WriteLine strNewText
objFile.Close