Home > database >  Change Text in Textfile with Search & Replace Regex | Batchfile
Change Text in Textfile with Search & Replace Regex | Batchfile

Time:09-23

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

CodePudding user response:

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
  • Related