【问题标题】:Batch command to take only first line from input批处理命令仅从输入中获取第一行
【发布时间】:2010-12-03 17:41:44
【问题描述】:

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

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

并输出“第一行输入”

【问题讨论】:

标签: batch-file


【解决方案1】:

为什么不通过管道使用 more +1 命令?

例如

输入一些东西 |更多+1

【讨论】:

  • 显示第一行的所有内容,OP需要直到第一行。见more /?: "+n -> 在第 n 行开始显示第一个文件"
【解决方案2】:

假设您的意思是 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

使用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

【讨论】:

  • 哦,如果您需要全部或最后一个输入行,则只需要for。使用set /p 获取第一行要容易得多。
  • 您还可以通过使用if not defined first 测试first 并在第一行之后取消设置来避免需要延迟扩展。
  • 不需要它?为什么?这是自切片面包以来最好的事情!几乎我的每个脚本都以该 setlocal 行开头;太棒了。
  • 好吧,如果我不是非常需要它,我会避免使用它,因为它仍然会在编写和阅读脚本时引发一些思考,即在哪里需要延迟扩展,何时不需要。
【解决方案3】:

你可以像这样得到第一行

set /p firstline=<file
echo %firstline%

【讨论】:

  • 那是因为 echo 只会显示第一行;使用它行if "%firstline%"=="foo" 将使用它的所有...
猜你喜欢
  • 2010-09-12
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
相关资源
最近更新 更多