如何在批处理脚本中读取文件的最后两行

时间:2014-12-11 05:59:57

标签: file batch-file batch-processing

我有一个Java程序,它在文件的最后两行中附加新的构建信息。 如何在批处理文件中阅读它们?

3 个答案:

答案 0 :(得分:4)

此代码段可以解决问题......

for /F "delims=" %%a in (someFile.txt) do (
   set "lastButOne=!lastLine!"
   set "lastLine=%%a"
)
echo %lastButOne%
echo %lastLine%

编辑完成TAIL.BAT已添加

可以修改此方法以获得可以由参数指定的更多行。以下文件是 tail.bat

@echo off
setlocal EnableDelayedExpansion

rem Tail command in pure Batch: Tail.bat filename numOfLines
rem Antonio Perez Ayala

for /F "delims=" %%a in (%1) do (
   set /A i=%2, j=%2-1
   for /L %%j in (!j!,-1,1) do (
      set "lastLine[!i!]=!lastLine[%%j]!
      set /A i-=1
   )
   set "lastLine[1]=%%a"
)
for /L %%i in (%2,-1,1) do if defined lastLine[%%i] echo !lastLine[%%i]!

2ND EDIT 新版TAIL.BAT已添加

以下版本效率更高:

@echo off
setlocal EnableDelayedExpansion

rem Tail command in pure Batch, version 2: Tail.bat filename numOfLines
rem Antonio Perez Ayala

set /A firstTail=1, lastTail=0
for /F "delims=" %%a in (%1) do (
   set /A lastTail+=1, lines=lastTail-firstTail+1
   set "lastLine[!lastTail!]=%%a"
   if !lines! gtr %2 (
      set "lastLine[!firstTail!]="
      set /A firstTail+=1
   )
)
for /L %%i in (%firstTail%,1,%lastTail%) do echo !lastLine[%%i]!

答案 1 :(得分:2)

这将解决问题,其中someFile.txt是您要从中读取行的文件:

for /f %%i in ('find /v /c "" ^< someFile.txt') do set /a lines=%%i
echo %lines%
set /a startLine=%lines% - 2
more /e +%startLine% someFile.txt > temp.txt
set vidx=0
for /F "tokens=*" %%A in (temp.txt) do (
    SET /A vidx=!vidx! + 1
    set localVar!vidx!=%%A
)
echo %localVar1%
echo %localVar2%
del temp.txt

答案 2 :(得分:1)

::change the values bellow with a relevant ones.
set "file=C:\some.file"
set "last_lines=2"


for /f %%a in ('findstr /R /N "^" "%file%" ^| find /C ":"') do @set lines=%%a
set /a m=lines-last_line
more +%m% "%file%"

直接从命令行:

C:\>set "file=C:\some.file"
C:\>set "last_lines=5"
C:\>(for /f %a in ('findstr /R /N "^" "%file%" ^| find /C ":"') do @set lines=%a)&@set /a m=lines-last_lines&call more +%m% "%file%"