onlyf
onlyf

Reputation: 873

VB - Find Replace on File

i have the following file :

/home/InputDirectory/DHddmmyy.txt
/home/InputDirectory2/DHddmmyy.txt
/home/InputDirectory3/DHddmmyy.txt

I would like to do the "Sed" equivalent from VB, so i dont have to call a cygwin sed to do this job, the end result should be :

/home/InputDirectory/DH250816.txt
/home/InputDirectory2/DH250816.txt
/home/InputDirectory3/DH250816.txt

The variable will be passed as a parameter into the script. Really inexperienced with anything VB, so any help would be greatly appreciated. The only thing close i ve found is this :

Dim TestString As String = "Shopping List"
' Returns "Shipping List".
Dim aString As String = Replace(TestString, "o", "i")

but how do i iterate over each line to perform that? Isnt there a way to do this for every line of a file? Thanks in advance.

Upvotes: 0

Views: 125

Answers (2)

Slai
Slai

Reputation: 22876

In your case you can just replace all at once

Dim text = File.ReadAllText("C:\1.txt")
text = text.Replace("ddmmyy", Now.ToString("ddMMyy")) 
File.WriteAllText("C:\1.txt", text)

Upvotes: 1

Johnlee Sam
Johnlee Sam

Reputation: 26

Try the below code. Here I have created a function which replaces "ddmmyy" with current date (in the same format)

Function FormatFileName(sFileName As String) As String
    Dim sReturnValue As String

    sReturnValue = Replace(sFileName, "ddmmyy", Format(Now(), "ddmmyy"), , ,   vbTextCompare)

    FormatFileName = sReturnValue
End Function

You may test the code by using below test procedure

Sub Process()
    Dim sOutputFileName As String

    sOutputFileName = FormatFileName("/home/InputDirectory/DHddmmyy.txt")
    Debug.Print sOutputFileName

    sOutputFileName = FormatFileName("/home/InputDirectory2/DHddmmyy.txt")
    Debug.Print sOutputFileName

    sOutputFileName = FormatFileName("/home/InputDirectory3/DHddmmyy.txt")
    Debug.Print sOutputFileName

End Sub

Hope it helps!!

Upvotes: 1

Related Questions