从一个文件逐行读取并使用批处理脚本写入另一个文件 [英] Reading line by line from one file and write to another file using batch script

查看:130
本文介绍了从一个文件逐行读取并使用批处理脚本写入另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我正在尝试从文件data.txt中提取字符串"AXX0000XXXA"的行号,然后逐行提取并打印target.txt文件,在此行到达查找行号的情况下,我要添加从文件temp.txt再多一行.代码在较少的记录数下工作正常(测试了150行-文件大小为100 kb),但是当我处理50K记录(文件大小为25MB)时,它需要花费更多的时间需要25分钟的处理时间.能否请您帮我在更少的时间内处理相同的内容.

In below code i am tring to fetch the line no of string "AXX0000XXXA" from file data.txt,then fetching line by line and printing target.txt file,in between if the line reach the find line no i am adding one more line from file temp.txt.The code is working fine with the less nos of records(tested with 150 lines-File Size 100 kb),but when i am processing with 50K records(File Size 25MB) it is taking more then 25 minutes to process.could you please help me how i will process same in less time.

@echo off
setlocal enabledelayedexpansion
for /f "delims=:" %%a in ('findstr /n "AXX0000XXXA" "C:\Users\23456\Desktop\data.txt"') do (set find_line=%%a)
set /a counter=0
for /f "usebackq delims=" %%b in (`"findstr /n ^^ C:\Users\23456\Desktop\data.txt"`) do ( 
set curr_line=%%b
set /a counter=!counter!+1 
if !counter! equ !find_line! (
    type temp.txt >> target.txt
)
call :print_line curr_line
)
endlocal

:print_line
setlocal enabledelayedexpansion
set line=!%1!
set line=!line:*:=!
echo !line!>>target.txt
endlocal

推荐答案

您的代码使用了三个本质上较慢的批处理文件构造:call命令,>>追加重定向和setlocal/endlocal,并且这些构造执行一次每个文件行!将子例程包含在原始代码中会更快,以避免使用callsetlocal命令,而echo !line!>>target.txt命令意味着打开文件,搜索末尾,追加数据并关闭文件,因此使用以下构造更快:(for ...) > target.txt只需打开一次文件.更改后的代码示例在Compo的答案中.

Your code uses three Batch file constructs that are inherently slow: call command, >> append redirection and setlocal/endlocal, and these constructs are executed once per each file line! It would be faster to include the subroutine into the original code to avoid the call and setlocal commands, and an echo !line!>>target.txt command imply open the file, search for the end, append the data and close the file, so it is faster to use this construct: (for ...) > target.txt that just open the file once. An example of a code with such changes is in Compo's answer.

这是解决此问题的另一种方法,当将搜索行置于文件开头时,该方法可能会运行得更快:

This is another method to solve this problem that may run faster when the search line is placed towards the beginning of the file:

@echo off
setlocal enabledelayedexpansion
for /f "delims=:" %%a in ('findstr /n "AXX0000XXXA" "C:\Users\23456\Desktop\data.txt"') do (set /A find_line=%%a-1)
call :processFile < "C:\Users\23456\Desktop\data.txt" > target.txt
goto :EOF


:processFile

rem Duplicate the first %find_line%-1 lines
for /L %%i in (1,1,%find_line%) do (
   set /P "line="
   echo !line!
)

rem Insert the additional line
type temp.txt

rem Copy the rest of lines
findstr ^^

exit /B

这篇关于从一个文件逐行读取并使用批处理脚本写入另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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