首页 > 解决方案 > 使用搜索和替换 + 正则表达式更改文本文件中的文本 | 批处理文件

问题描述

我需要编写一个 .bat/.cmd/.vbs 文件来更改文本文件的文本,我还需要正则表达式。

我有以下文本文件作为 .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"

现在我想做以下正则表达式搜索和替换:

(1. Replace)
Search: "
Replace: (nothing)
(2. Replace)
Search: .+(?=web)
Replace: (nothing)

现在文本应该是:

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\

这应该导致:

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

由于我对批处理文件一无所知,我希望您能进一步帮助我或分享某些方法或注意事项。

提前感谢您的反馈和最好的问候诺埃尔

我已经测试过的内容——我知道如何将红色等文本更改为蓝色:

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

标签: regexvbscript

解决方案


我希望这会有所帮助......正则表达式可以跳过几步,只需抓取字符串(网络......),而无需多余的步骤。产生所需的模式输出。

请注意,您需要将此版本更新回您的文件 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

推荐阅读