2009-10-04 47 views
3

我正在寻找一个DOS批处理程序,需要一个文件:批处理命令只取第一线与输入

First input line 
Second input line 
Third input line... 

和输出“首先输入线”

+2

查看重复:http://stackoverflow.com/questions/130116/dos-batch-commands-to-read-first-line-from-text-file – 2009-10-04 13:40:30

+0

@ire_and_curses - 谢谢,投票结束。 – ripper234 2013-02-28 10:25:21

回答

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 

无线TH的infile.txt输入文件为:

line 1 
line 2 
line 3 

这将输出:

line 1 

这将仍然过程所有行,它只是不会如果你想打印那些超越1号线真正停止加工,使用这样的:

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

或者你可以去让你的手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 
+0

哦,如果你需要全部或最后一个输入行,你只需要'for'。使用'set/p'获得第一行比较容易。 – Joey 2009-10-04 13:51:39

+0

您也可以避免需要延迟扩展,方法是先测试'first'(如果未先定义),并在第一行之后取消设置。 – Joey 2009-10-04 13:52:53

+0

避免需要吗?为什么?这是自切片面包以来最好的事情!几乎每一个脚本都以setlocal行开头;这个棒极了。 – paxdiablo 2009-10-05 02:10:03

13

你可以得到这样

第一线
set /p firstline=<file 
echo %firstline% 
-2

为什么不通过管道使用更多的+1命令?

例如

键入东西|更多+1

+1

显示**第一行中的所有内容**,操作系统需要**,直到**第一行。参见'more /?':“+ n - >在第n行开始显示第一个文件” – TWiStErRob 2015-06-18 21:10:13