淮南市文章资讯

Windows批处理BAT中实现文本文件字符串替换

2026-05-05 10:33:02 浏览次数:0
详细信息

方法1:使用 set 命令(适合小文件)

@echo off
setlocal enabledelayedexpansion

set "input=test.txt"
set "output=new_test.txt"
set "oldstr=旧文本"
set "newstr=新文本"

if not exist "%input%" (
    echo 文件不存在: %input%
    exit /b
)

(for /f "usebackq delims=" %%a in ("%input%") do (
    set "line=%%a"
    set "line=!line:%oldstr%=%newstr%!"
    echo !line!
)) > "%output%"

echo 替换完成

方法2:使用 findstr 命令(简单替换)

@echo off
set "input=test.txt"
set "output=new_test.txt"
set "oldstr=要替换的文本"
set "newstr=替换后的文本"

type "%input%" | findstr /v /n "^$" > "%input%.tmp"

(for /f "tokens=1* delims=:" %%a in ('findstr /n "^" "%input%.tmp"') do (
    set "line=%%b"
    call :replace
)) > "%output%"

del "%input%.tmp"
echo 替换完成
goto :eof

:replace
setlocal enabledelayedexpansion
set "line=!line:%oldstr%=%newstr%!"
echo !line!
endlocal
goto :eof

方法3:使用 sed 命令(需要安装)

如果有 sed 工具(可从 Git for Windows 等获取):

@echo off
set "input=test.txt"
set "output=new_test.txt"
set "oldstr=旧文本"
set "newstr=新文本"

REM sed -i 表示直接修改原文件
sed "s/%oldstr%/%newstr%/g" "%input%" > "%output%"

方法4:使用 PowerShell(推荐,功能强大)

@echo off
set "input=test.txt"
set "output=new_test.txt"
set "oldstr=旧文本"
set "newstr=新文本"

REM 使用 PowerShell 进行替换
powershell -Command "(Get-Content '%input%') -replace '%oldstr%', '%newstr%' | Set-Content '%output%'"

方法5:使用 JScript(内置于 Windows)

创建 replace.vbs 脚本:

Set args = WScript.Arguments
If args.Count < 4 Then
    WScript.Echo "用法: cscript replace.vbs 输入文件 输出文件 旧字符串 新字符串"
    WScript.Quit
End If

inputFile = args(0)
outputFile = args(1)
oldStr = args(2)
newStr = args(3)

Set fso = CreateObject("Scripting.FileSystemObject")
Set input = fso.OpenTextFile(inputFile, 1)
Set output = fso.OpenTextFile(outputFile, 2, True)

Do While Not input.AtEndOfStream
    line = input.ReadLine
    line = Replace(line, oldStr, newStr)
    output.WriteLine line
Loop

input.Close
output.Close

然后在批处理中调用:

@echo off
cscript //nologo replace.vbs "test.txt" "new_test.txt" "旧文本" "新文本"

方法6:带特殊字符处理的版本

@echo off
setlocal enabledelayedexpansion

set "input=input.txt"
set "output=output.txt"
set "oldstr=要&替换的<特殊>文本"
set "newstr=新&文本"

REM 处理特殊字符
set "oldstr_esc=!oldstr:&=^&!"
set "oldstr_esc=!oldstr_esc:<=^<!"
set "oldstr_esc=!oldstr_esc:>=^>!"
set "oldstr_esc=!oldstr_esc:|=^|!"

set "newstr_esc=!newstr:&=^&!"
set "newstr_esc=!newstr_esc:<=^<!"
set "newstr_esc=!newstr_esc:>=^>!"
set "newstr_esc=!newstr_esc:|=^|!"

(for /f "usebackq delims=" %%a in ("%input%") do (
    set "line=%%a"
    call set "line=%%line:!oldstr_esc!=!newstr_esc!%%"
    echo(!line!
)) > "%output%"

echo 替换完成

推荐方案

PowerShell 方法通常是最佳选择,因为它:

内置于现代 Windows 系统 支持正则表达式 处理大文件性能好 能正确处理各种特殊字符

相关推荐