[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

实现对文件指定行的读取的批处理小函数

  经常要对文件的指定行进行读取,特写了一个读取文件指定行的小程序段(ReadLine.Bat),方面以后调用。

  使用也比较简单:"Call ReadLine <文件名> <跳过的行数> <读取行数>"就可以了。比如在一个批处理里加上一句"Call ReadLine a.txt 5 7",那么将跳过a.txt文件的前5行,显示下面的7行字符,也包含空行。也可以不指定第三个参数。

ReadLine.Bat
  1. @echo off&SetLocal ENABLEDELAYEDEXPANSION
  2. if "%1"=="" (goto --help) else (set file=%~s1)
  3. if "%2"=="" (set first="delims=: tokens=1*") else (set first="skip=%2 delims=: tokens=1*")
  4. if "%3"=="" (
  5.         for /f %first% %%a in ('findstr /n .* %file%') do echo/%%b
  6.         goto :EOF
  7. )
  8. set last=%3
  9. set loop=0
  10. for /f %first% %%a in ('findstr/n .* %file%') do (
  11.         if not defined lxmxn (echo/%%b&set /a loop+=1) else (goto :EOF)
  12.         if "!loop!"=="%last%" set lxmxn=Nothing
  13. )
  14. GOTO :EOF
  15. :--help
  16. echo/======================================
  17. echo/本程序段需要带参数才能正常运行
  18. echo/&echo/Usage:&echo/Call ReadLine ^<文件名^> ^<跳过行数^> ^<读取行数^>
  19. echo/&echo/例如:call ReadLine aa.txt 5 7 ,将跳过aa.txt文件的前5行,读取下面的7行字符
  20. echo/&echo/如果^<跳过行数^>没有指定,就从文件第一行读取
  21. echo/&echo/指定^<读取行数^>时必须指定^<跳过行^>
  22. echo/======================================
  23. goto :eof
复制代码
原文地址:http://www.cn-dos.net/forum/viewthread.php?tid=28639
我帮忙写的代码不需要付钱。如果一定要给,请在微信群或QQ群发给大家吧。
【微信公众号、微信群、QQ群】http://bbs.bathome.net/thread-3473-1-1.html
【支持批处理之家,加入VIP会员!】http://bbs.bathome.net/thread-67716-1-1.html

test_1.bat
  1. @echo off
  2. REM 读取哪个文件
  3. set "SrcFile=C:\Test\1.txt"
  4. REM 获取第几行
  5. set "DstRow=2"
  6. setlocal enabledelayedexpansion
  7. for /f "tokens=1* delims=:" %%i in ('findstr /n .* "%SrcFile%"') do (
  8.     set /a "CurRow+=1"
  9.     if !CurRow! equ %DstRow% (
  10.         echo,%%j
  11.         goto :End
  12.     )
  13. )
  14. :End
  15. pause
复制代码
test_2.bat
  1. @echo off
  2. REM 读取哪个文件
  3. set "SrcFile=C:\Test\1.txt"
  4. REM 获取第几行
  5. set "DstRow=2"
  6. set "CurRow=0"
  7. for /f "tokens=1* delims=:" %%i in ('findstr /n .* "%SrcFile%"') do (
  8.     if %%i equ %DstRow% (
  9.         echo,%%j
  10.         goto :End
  11.     )
  12. )
  13. :End
  14. pause
复制代码
test_3.bat
  1. @echo off
  2. REM 读取哪个文件
  3. set "SrcFile=C:\Test\1.txt"
  4. REM 获取第几行
  5. set "DstRow=2"
  6. if %DstRow% equ 1 (
  7.     set /p str=<"%SrcFile%"
  8.     call echo,%%str%%
  9.     goto :End
  10. )
  11. set /a "IgnoreCount=DstRow-1"
  12. call :GetRow %%IgnoreCount%%
  13. goto :eof
  14. :GetRow
  15. for /f "skip=%1 delims=" %%i in ('type "%SrcFile%"') do (
  16.     echo,%%i
  17.     goto :End
  18. )
  19. :End
  20. pause
复制代码
我帮忙写的代码不需要付钱。如果一定要给,请在微信群或QQ群发给大家吧。
【微信公众号、微信群、QQ群】http://bbs.bathome.net/thread-3473-1-1.html
【支持批处理之家,加入VIP会员!】http://bbs.bathome.net/thread-67716-1-1.html

TOP

感谢大神分享,正好需要

TOP

返回列表