首页 > 解决方案 > 适用于 Windows 的本机 cmd tail 命令

问题描述

我正在寻找构建一个tail仅使用 native 来读取 Windows 上的日志文件cmd

有多种读取文件的方法:

type file.txt
more file.txt

但是,它们没有从文件读取更新的默认选项,因此不代表tail.

标签: batch-filecmd

解决方案


通过一些小技巧并使用more来读取文件,跳过之前已经读取的内容,我们能够“几乎”实时读取tail文件。

@echo off & set cnt=0
if "%~1" == "" echo no file specified, usage: "tail.cmd <filename>"  & goto :eof
if not exist "%~1" echo file "%~1" does not exist & goto :eof
:tail_sub
2>nul (>>"%~1" echo off) && (goto :file) || (goto :tail_sub)
:file
for /f "tokens=1*delims=]" %%i in ('more "%~1" +%cnt% ^| find /v /n ""') do (
    set "line=%%j"
    set /a cnt+=1
    call echo(%%line%%
)
goto :tail_sub

目前,在不添加 atimeout来减慢无限循环的情况下,它会消耗大约 5.6MB 的内存,这在我看来是非常可以接受的。这还没有处理所有特殊字符,比如|<>&,但我会花一些时间来满足我能想到的所有场景。


推荐阅读