找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 25271|回复: 2

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

[复制链接]
发表于 2009-5-8 12:43:01 | 显示全部楼层 |阅读模式
  经常要对文件的指定行进行读取,特写了一个读取文件指定行的小程序段(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
发表于 2012-10-19 15:40:52 | 显示全部楼层
感谢大神分享,正好需要
 楼主| 发表于 2022-10-18 14:48:43 | 显示全部楼层
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
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-16 20:18 , Processed in 0.016058 second(s), 8 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表