【问题标题】:Is there a way to emulate the head command in Windows cmd?有没有办法在 Windows cmd 中模拟 head 命令?
【发布时间】:2015-06-11 16:58:00
【问题描述】:

我正在尝试获取一个巨大文本文件(数据库表的 10 万条记录)的前几行,但它太大而无法在文本编辑器中真正进行操作。

如果我在 linux 中,我会使用 head。我知道我可以使用

更多 +99995 dbfile.txt

获取文件中的最后 5 行。是否有一种等效(且简单)的方法来获取 FIRST 行并像这样记录?

谢谢。

(请注意,必须能够登录)。

【问题讨论】:

标签: logging cmd tail head


【解决方案1】:

head.bat

@echo off

setlocal DISABLEDELAYEDEXPANSION

set "NUM=%~1"
if "%NUM%" == "" set NUM=0

set LINE_INDEX=0

for /F "usebackq delims=" %%i in (`findstr /B /N /R /C:".*"`) do (
  set LINE_STR=%%i
  call :IF_OR_PRINT %%NUM%% NEQ 0 if %%LINE_INDEX%% GEQ %%NUM%% && exit /b 0
  set /A LINE_INDEX+=1
)

exit /b 0

:IF_OR_PRINT
if %* exit /b 0
setlocal ENABLEDELAYEDEXPANSION
set OFFSET=0
:OFFSET_LOOP
set CHAR=!LINE_STR:~%OFFSET%,1!
if not "!CHAR!" == ":" ( set /A OFFSET+=1 && goto OFFSET_LOOP )
set /A OFFSET+=1
echo.!LINE_STR:~%OFFSET%!
exit /b 1

用法

类型文件 | head.bat 1000

特点

  • 打印所有字符,包括!%^&|> 等控制字符。
  • 不消耗空行。

问题

  • findstr 截断长度超过 8180 个字符的行(“FINDSTR: Line NNN is too long”消息)
  • 没那么快,在 3.2GHz AMD 处理器上打印约 2000 行大约 8 秒

【讨论】:

    【解决方案2】:

    为什么要在 Windows 组中提及 Unix 之类的玩具。你不聪明。

    剪切

    filter cut {t|b} {i|x} NumOfLines
    

    从文件的顶部或底部减少行数。

    t - top of the file
    b - bottom of the file
    i - include n lines
    x - exclude n lines
    

    示例

    cscript //nologo filter cut t i 5 < "%systemroot%\win.ini"
    

    脚本

    Set Arg = WScript.Arguments
    set WshShell = createObject("Wscript.Shell")
    Set Inp = WScript.Stdin
    Set Outp = Wscript.Stdout
    Set rs = CreateObject("ADODB.Recordset")
    With rs
        .Fields.Append "LineNumber", 4 
    
        .Fields.Append "Txt", 201, 5000 
        .Open
        LineCount = 0
        Do Until Inp.AtEndOfStream
            LineCount = LineCount + 1
            .AddNew
            .Fields("LineNumber").value = LineCount
            .Fields("Txt").value = Inp.readline
            .UpDate
        Loop
    
        .Sort = "LineNumber ASC"
    
        If LCase(Arg(1)) = "t" then
            If LCase(Arg(2)) = "i" then
                .filter = "LineNumber < " & LCase(Arg(3)) + 1
            ElseIf LCase(Arg(2)) = "x" then
                .filter = "LineNumber > " & LCase(Arg(3))
            End If
        ElseIf LCase(Arg(1)) = "b" then
            If LCase(Arg(2)) = "i" then
                .filter = "LineNumber > " & LineCount - LCase(Arg(3))
            ElseIf LCase(Arg(2)) = "x" then
                .filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
            End If
        End If
    
        Do While not .EOF
            Outp.writeline .Fields("Txt").Value
    
            .MoveNext
        Loop
    End With
    

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 2020-07-02
      • 2011-12-25
      • 2012-08-15
      • 2016-03-19
      • 2014-03-22
      • 2011-04-21
      • 2016-03-24
      • 1970-01-01
      相关资源
      最近更新 更多