batch-filefindedittext-fileslines

Batch / Find And Edit Lines in TXT file


I want to create a batch while which finds specific lines in a batch file and are able to edit these lines.

Example:

//TXT FILE//

ex1
ex2
ex3
ex4

i want to let the batch file find 'ex3' and edit this to 'ex5' to let it look like this:

ex1
ex2
ex5
ex4

Solution

  • On a native Windows install, you can either use batch(cmd.exe) or vbscript without the need to get external tools. Here's an example in vbscript:

    Set objFS = CreateObject("Scripting.FileSystemObject")
    strFile = "c:\test\file.txt"
    Set objFile = objFS.OpenTextFile(strFile)
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        If InStr(strLine,"ex3")> 0 Then
            strLine = Replace(strLine,"ex3","ex5")
        End If 
        WScript.Echo strLine
    Loop    
    

    Save as myreplace.vbs and on the command line:

    c:\test> cscript /nologo myreplace.vbs  > newfile
    c:\test> ren newfile file.txt