使用 Windows 批处理文件从 txt 文件中仅读取 x 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3805036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read ONLY x lines from a txt file with a windows batch file
提问by LittleBobbyTables - Au Revtheitroad
How can I read only X lines from a a.txt file?
如何从 a.txt 文件中只读取 X 行?
The file contains all the names of a directory, I would like to read only x lines. X can be a number that can varies from 1 to 99
该文件包含目录的所有名称,我只想读取 x 行。X 可以是 1 到 99 之间的数字
回答by LittleBobbyTables - Au Revtheitroad
You'll need to modify this based on your needs, but the script below will loop through the file 'directories.txt', and ECHO the contents of the line until you hit the maximum number of lines set in maxlines
.
您需要根据需要修改它,但下面的脚本将循环遍历文件“directories.txt”,并回显该行的内容,直到达到 .txt 中设置的最大行数maxlines
。
@ECHO OFF
setlocal enabledelayedexpansion
SET /A maxlines=1
SET /A linecount=0
FOR /F %%A IN (directories.txt) DO (
IF !linecount! GEQ %maxlines% GOTO ExitLoop
ECHO %%A
SET /A linecount+=1
)
:ExitLoop
PAUSE
回答by ghostdog74
you can use vbscript. Here's an example
你可以使用 vbscript。这是一个例子
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strNum = objArgs(0)
strFile=objArgs(1)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfLine
If CInt(objFile.Line) > CInt(strNum) Then
Exit Do
End If
strLine=objFile.ReadLine
WScript.Echo strLine
Loop
save as myscript.vbs and
另存为 myscript.vbs 和
c:\test> cscript //nologo myscript.vbs 99 file
Or if have the luxury to install tools, you can download sedor gawkfor windows . Then on the command line
或者,如果有安装工具的奢侈,您可以下载sed或 gawkfor windows 。然后在命令行
sed.exe "99q" file
gawk.exe "NR>2{exit}1" file