我编写了一个批处理脚本来替换文本文件中的字符串。
以下是剧本。
@echo off &setlocal
set "search=%1"
set "replace=%2"
set "textfile=Input.txt"
set "newfile=Output.txt"
(for /f "delims=" %%i in (%textfile%) do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%newfile%"
del %textfile%
rename %newfile% %textfile%
但对于一个12MB的文件,它需要接近7分钟。我希望它不到一分钟。我们可以使用 find或findstr 命令来减少所需的时间吗?
答案 0 :(得分:24)
试一试:
@echo off
setlocal
call :FindReplace "findstr" "replacestr" input.txt
exit /b
:FindReplace <findstr> <replstr> <file>
set tmp="%temp%\tmp.txt"
If not exist %temp%\_.vbs call :MakeReplace
for /f "tokens=*" %%a in ('dir "%3" /s /b /a-d /on') do (
for /f "usebackq" %%b in (`Findstr /mic:"%~1" "%%a"`) do (
echo(&Echo Replacing "%~1" with "%~2" in file %%~nxa
<%%a cscript //nologo %temp%\_.vbs "%~1" "%~2">%tmp%
if exist %tmp% move /Y %tmp% "%%~dpnxa">nul
)
)
del %temp%\_.vbs
exit /b
:MakeReplace
>%temp%\_.vbs echo with Wscript
>>%temp%\_.vbs echo set args=.arguments
>>%temp%\_.vbs echo .StdOut.Write _
>>%temp%\_.vbs echo Replace(.StdIn.ReadAll,args(0),args(1),1,-1,1)
>>%temp%\_.vbs echo end with
答案 1 :(得分:8)
这使用名为repl.bat
的帮助程序批处理文件 - 从https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
将repl.bat
放在与批处理文件相同的文件夹中或放在路径上的文件夹中。
Repl.bat是使用本机Windows脚本的混合批处理文件,比常规批处理脚本快得多。
L
开关使文本搜索并替换文字字符串,我希望在现代PC上几秒内完成12 MB文件。
@echo off &setlocal
set "search=%~1"
set "replace=%~2"
set "textfile=Input.txt"
set "newfile=Output.txt"
call repl.bat "%search%" "%replace%" L < "%textfile%" >"%newfile%"
del "%textfile%"
rename "%newfile%" "%textfile%"
答案 2 :(得分:7)
只需从here
下载放屁(查找和替换文字)即可在CMD中使用它(为了便于使用,我将fart文件夹添加到我的路径变量中)
这是一个例子:
fart -r "C:\myfolder\*.*" findSTR replaceSTR
此命令将在C:\ myfolder和所有子文件夹中搜索并用replaceSTR替换findSTR
-r表示递归处理子文件夹。
放屁非常快捷
答案 3 :(得分:6)
使用Bat / Powershell的变种(需要.net框架):
replace.bat:
@echo off
call:DoReplace "Findstr" "replacestr" test.txt test1.txt
exit /b
:DoReplace
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4>Rep.ps1
Powershell.exe -executionpolicy ByPass -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
echo Done
pause
答案 4 :(得分:4)
这个,伙计们怎么样?
set search=%1
set replace=%2
set textfile=Input.txt
set line1=with open('%textfile%', 'rw') as f:
set line2=f.write(f.read().replace('%search%', '%replace%'))
python -c "%line1%%line2%"
Muhahaha
编辑:
疯狂的oneliner
python -c "with open('%textfile%', 'rw') as f: f.write(f.read().replace('%search%', '%replace%'))"
答案 5 :(得分:4)
试试这个:
@echo off &setlocal
setlocal enabledelayedexpansion
set "search=%1"
set "replace=%2"
set "textfile=Input.txt"
set "newfile=Output.txt"
(for /f "delims=" %%i in (%textfile%) do (
set "line=%%i"
set "line=!line:%search%=%replace%!"
echo(!line!
))>"%newfile%"
del %textfile%
rename %newfile% %textfile%
endlocal