实现对文件指定行的读取的批处理小函数
经常要对文件的指定行进行读取,特写了一个读取文件指定行的小程序段(ReadLine.Bat),方面以后调用。使用也比较简单:"[color=Blue]Call ReadLine <文件名> <跳过的行数> <读取行数>[/color]"就可以了。比如在一个批处理里加上一句"Call ReadLine a.txt 5 7",那么将跳过a.txt文件的前5行,显示下面的7行字符,也包含空行。也可以不指定第三个参数。
[color=Blue]ReadLine.Bat[/color][code]@echo off&SetLocal ENABLEDELAYEDEXPANSION
if "%1"=="" (goto --help) else (set file=%~s1)
if "%2"=="" (set first="delims=: tokens=1*") else (set first="skip=%2 delims=: tokens=1*")
if "%3"=="" (
for /f %first% %%a in ('findstr /n .* %file%') do echo/%%b
goto :EOF
)
set last=%3
set loop=0
for /f %first% %%a in ('findstr/n .* %file%') do (
if not defined lxmxn (echo/%%b&set /a loop+=1) else (goto :EOF)
if "!loop!"=="%last%" set lxmxn=Nothing
)
GOTO :EOF
:--help
echo/======================================
echo/本程序段需要带参数才能正常运行
echo/&echo/Usage:&echo/Call ReadLine ^<文件名^> ^<跳过行数^> ^<读取行数^>
echo/&echo/例如:call ReadLine aa.txt 5 7 ,将跳过aa.txt文件的前5行,读取下面的7行字符
echo/&echo/如果^<跳过行数^>没有指定,就从文件第一行读取
echo/&echo/指定^<读取行数^>时必须指定^<跳过行^>
echo/======================================
goto :eof[/code]原文地址:[url]http://www.cn-dos.net/forum/viewthread.php?tid=28639[/url] 感谢大神分享,正好需要 test_1.bat[code]@echo off
REM 读取哪个文件
set "SrcFile=C:\Test\1.txt"
REM 获取第几行
set "DstRow=2"
setlocal enabledelayedexpansion
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "%SrcFile%"') do (
set /a "CurRow+=1"
if !CurRow! equ %DstRow% (
echo,%%j
goto :End
)
)
:End
pause[/code]test_2.bat[code]@echo off
REM 读取哪个文件
set "SrcFile=C:\Test\1.txt"
REM 获取第几行
set "DstRow=2"
set "CurRow=0"
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "%SrcFile%"') do (
if %%i equ %DstRow% (
echo,%%j
goto :End
)
)
:End
pause[/code]test_3.bat[code]@echo off
REM 读取哪个文件
set "SrcFile=C:\Test\1.txt"
REM 获取第几行
set "DstRow=2"
if %DstRow% equ 1 (
set /p str=<"%SrcFile%"
call echo,%%str%%
goto :End
)
set /a "IgnoreCount=DstRow-1"
call :GetRow %%IgnoreCount%%
goto :eof
:GetRow
for /f "skip=%1 delims=" %%i in ('type "%SrcFile%"') do (
echo,%%i
goto :End
)
:End
pause[/code]
页:
[1]