【问题标题】:Find and Replace/Append text in a file using batch or vbs使用批处理或 vbs 在文件中查找和替换/附加文本
【发布时间】:2012-05-12 21:03:44
【问题描述】:

我在不同的子目录下有许多同名的文件,分隔符为“}”。我想找到一组特定的文本并在分隔符之前附加一些新文本。例如:

folder1\sample.css
    .asd {}
    .bar {}
folder2\sample.css
    .foo {}
    .bar {}

所有 sample.txt 文件应如下所示:

..
.foo {display:none;}
..

我将如何使用 vbs、powershell 或最好是批处理文件来完成此操作? 类似的东西:

SETLOCAL ENABLEDELAYEDEXPANSION
for /r %%f in (*.txt) do (
    for /f "delims=}" %%a in (%%f) do (
        set str=%%a
        REM modify the variable
        REM replace the line with the variable
    )
)

编辑: 我得到了它的工作,但我相信这可以写得更好,具有更多的可重用性。

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /r %%f in (index.css) do (
    BatchSubstitute.bat ".foo {" ".foo { display:none;" %%f>%%f.new
    del %%f
    BatchSubstitute.bat ".bar {" ".bar { display:none;" %%f.new>%%f
    del %%f.new
    BatchSubstitute.bat ".asd {" ".asd { display:none;" %%f>%%f.new
    del %%f
    ren %%f.new index.css
)

BatchSubstitute.bat

@echo off
REM -- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

::BatchSubstitude - parses a File line by line and replaces a substring"
::syntax: BatchSubstitude.bat OldStr NewStr File
::          OldStr [in] - string to be replaced
::          NewStr [in] - string to replace with
::          File   [in] - file to be parsed
:$changed 20100115
:$source http://www.dostips.com
if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B"
    if defined line (
        call set "line=echo.%%line:%~1=%~2%%"
        for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X
    ) ELSE echo.
)

【问题讨论】:

  • CMD 不适合这个。我建议您使用您更熟悉的 VBS 和 Powershell。

标签: vbscript batch-file cmd


【解决方案1】:

您可以使用这个批处理文件:http://www.dostips.com/?t=Batch.FindAndReplace

在您的文件循环中调用该文件,在该文件循环中查找/替换.foo {}.foo{display:none;}

可能有比使用此查找/替换批处理更好的查找/替换二进制文件,但它可能会完成这项工作。

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2020-08-22
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多