1

我有一个包含许多子文件夹的文件夹,每个子文件夹都包含几十个.mht不同长度的文件。我需要帮助创建一个批处理脚本来过滤掉这个特定的字符串:

"</BODY></HTML>"

在将其添加回末尾之前,我可以将这是我到目前为止所拥有的:

setlocal enabledelayedexpansion

for /r %%a in (*.mht) do (
    for /f "skip=11" %%b in (%%a) do (if %%b=="</BODY></HTML>" del %%b)
    echo "stuff to add">>%%a
    echo "</BODY></HTML>">>%%a
)

有什么方法可以修复我当前的脚本,或者你们中的任何人都知道更简单的方法吗?

注意:我尝试将除不需要的字符串之外的所有内容复制到临时文件,但前 11 行包含特殊字符,例如:| , . :

4

1 回答 1

1

更新

我添加了一个新脚本,它将用所需代码替换搜索词。该脚本可以处理特殊字符。


限制

  1. 前导右括号]字符将从行首开始修剪。不是问题,因为 HTML 中不应有以该字符开头的行。(如果需要,可以修复)
  2. 百分号%字符不能用于搜索词或替换词。

笔记

  1. 行不能包含奇数个双引号",所以我将双引号加倍""以确保偶数。这意味着如果您在任一字符串中有引号,它们也必须加倍!
  2. 要使用该脚本,只需在以下代码行中将搜索词替换词替换为您想要的内容。

    set "_=%_:搜索词=替换词%"

新脚本.bat

@echo off
setlocal EnableExtensions DisableDelayedExpansion

:: Limitations
:: 1. Any leading close bracket ] characters will be trimmed due to delims=].

for /r %%F in (html.txt) do if exist "%%~fF" (
    for /f "tokens=1,* delims=]" %%K in ('type "%%~fF" ^| find /n /v ""') do (
        set "_=%%L"
        call :Expand_
    )
)
goto End


:Expand_
:: NULL is a blank line or line with only a close bracket ].
if not defined _ echo. & goto :eof
:: Ensure even number of double quotation marks.
set "_=%_:"=""%"
:: Inject the code.
set "_=%_:</body>=<code>To Inject</code></body>%"
:: Escape batch special characters.
set "_=%_:^=^^%"
set "_=%_:<=^<%"
set "_=%_:>=^>%"
set "_=%_:&=^&%"
set "_=%_:|=^|%"
:: Revert quotations.
set "_=%_:""="%"
:: Display
echo(%_%
goto :eof


:End
endlocal
pause >nul

原来的

这应该做你想要的。无需延迟扩展。应该支持所有特殊字符。

限制

  1. 前导右括号]字符将被修剪。不是问题,因为 HTML 中不应有以右括号字符开头的行。 (如果需要,可以修复。)
  2. 百分号%字符不能用于搜索词或替换词。

笔记

  1. 行不能包含奇数个双引号",所以我将双引号加倍""以确保偶数。这意味着如果字符串中有要匹配的引号,它们也必须加倍。(不适用于您的场景)
  2. 不能在此行周围使用延迟扩展,for /f %%S in ('echo "%xLine%"^| find /i "</body>"') do (否则!感叹号会导致问题。

脚本.bat

@echo off
setlocal EnableExtensions

for /r %%F in (*.mht) do if exist "%%~fF" (
    rem Limitation - Any leading close bracket ] characters will be trimmed.
    for /f "tokens=1,* delims=]" %%K in ('type "%%~fF" ^| find /n /v ""') do (
        set "xLine="%%L""
        call :Match
        echo(%%L>>"%%~dpF\new_%%~nF%%~xF"
    )
    rem del "%%~fF"
    rem ren "%%~dpF\new_%%~nF%%~xF" "%%~nxF"
)
goto End


:Match
setlocal EnableExtensions DisableDelayedExpansion
rem Double the double quotations to ensure even number of double quotations.
set "xLine=%xLine:"=""%"
for /f %%S in ('echo "%xLine%"^| find /i "</body>"') do (
    rem Add your code to inject here.  Copy the template echo below.
    rem Note that special characters need to be escaped.
    echo Inject Code>>"%%~dpF\new_%%~nF%%~xF"
)
endlocal
goto :eof


:End
endlocal
pause >nul

这会将新文件输出到new_<filename>.mht 如果您想用新文件替换旧文件,只需从and命令rem之前删除该命令。delren

于 2013-01-14T22:31:01.850 回答