批处理脚本可在一分钟内查找和替换文本文件中的字符串,文件最大为 12 MB [英] Batch script to find and replace a string in text file within a minute for files up to 12 MB

查看:11
本文介绍了批处理脚本可在一分钟内查找和替换文本文件中的字符串,文件最大为 12 MB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个批处理脚本来替换文本文件中的字符串.

I have written a batch script to replace a string in text file.

以下是脚本.

@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 命令来减少花费的时间吗?

But for a 12MB file, it is taking close to 7 min. I want it to be under a minute. Can we make use of find or findstr command to reduce the time taken?

推荐答案

试试这个:

@echo off
setlocal

call :FindReplace "findstr" "replacestr" input.txt

exit /b 

:FindReplace <findstr> <replstr> <file>
set tmp="%temp%	mp.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

这篇关于批处理脚本可在一分钟内查找和替换文本文件中的字符串,文件最大为 12 MB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆