批处理命令仅从输入中获取第一行

rip*_*234 3 batch-file

我正在寻找一个带有文件的DOS批处理程序:

First input line
Second input line
Third input line...
Run Code Online (Sandbox Code Playgroud)

并输出"第一输入线"

gho*_*g74 14

你可以像这样得到第一行

set /p firstline=<file
echo %firstline%
Run Code Online (Sandbox Code Playgroud)


pax*_*blo 10

假设你的意思是Windows的cmd解释(我会感到惊讶,如果你真的还在使用DOS),下面的脚本会做你想要什么:

@echo off
setlocal enableextensions enabledelayedexpansion
set first=1
for /f "delims=" %%i in (infile.txt) do (
    if !first!==1 echo %%i
    set first=0
)
endlocal
Run Code Online (Sandbox Code Playgroud)

输入文件infile.txt为:

line 1
line 2
line 3
Run Code Online (Sandbox Code Playgroud)

这将输出:

line 1
Run Code Online (Sandbox Code Playgroud)

这仍将处理所有行,它不会打印超出第1行的那些行.如果您想要实际停止处理,请使用以下内容:

@echo off
setlocal enableextensions enabledelayedexpansion
for /f "delims=" %%i in (infile.txt) do (
    echo %%i
    goto :endfor
)
:endfor
endlocal
Run Code Online (Sandbox Code Playgroud)

或者您可以直接使用CygwinGnuWin32并使用该head程序.这就是我要做的.但是,如果这不是一个选项(某些工作场所不允许),您可以在Windows中创建类似的cmd文件,如下所示winhead.cmd:

@echo off
setlocal enableextensions enabledelayedexpansion

if x%1x==xx goto :usage
if x%2x==xx goto :usage

set /a "linenum = 0"
for /f "usebackq delims=" %%i in (%1) do (
    if !linenum! geq %2 goto :break1
    echo %%i
    set /a "linenum = linenum + 1"
)
:break1
endlocal
goto :finish

:usage
echo.winhead ^<file^> ^<numlines^>
echo.   ^<file^>
echo.      is the file to process
echo.      (surround with double quotes if it contains spaces).
echo.   ^<numlines^>
echo.      is the number of lines to print from file start.
goto :finish

:finish
endlocal
Run Code Online (Sandbox Code Playgroud)