在 Windows Batch 中打印文本文件的特定行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3361689/
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
Printing specific lines of a textual file in Windows Batch
提问by Yon
I'm trying to find a fairly efficient way of printing specific lines of a textual file in Windows Batch. It must be Windows Batch and no other tools (gwk.exe, perl, python, javascript, etc. etc.). I have a list of line numbers (1, 7, 15, 20, etc.) which can be fairly long (dozens if not more).
我试图找到一种相当有效的方法来打印 Windows Batch 中文本文件的特定行。它必须是 Windows Batch,没有其他工具(gwk.exe、perl、python、javascript 等)。我有一个行号列表(1、7、15、20 等),这些行号可能很长(如果不是更多,则是几十个)。
Any ideas?
有任何想法吗?
Thanks!
谢谢!
回答by paxdiablo
Here's a script which shows how you can do it. It's not the most efficient in the world but command scripts rarely are :-)
这是一个脚本,它展示了如何做到这一点。它不是世界上最高效的,但命令脚本很少是 :-)
@setlocal enableextensions enabledelayedexpansion
@echo off
set lines=1 7 15 20
set curr=1
for /f "delims=" %%a in ('type infile.txt') do (
for %%b in (!lines!) do (
if !curr!==%%b echo %%a
)
set /a "curr = curr + 1"
)
endlocal
When run over the file containing line N
for N ranging from 1 to 24, you get:
当运行包含line N
从 1 到 24 的 N的文件时,您会得到:
line 1
line 7
line 15
line 20
as expected.
正如预期的那样。
I wouldn't be using this for a very large number of line numbers (since the inner loop runs that many times for everyline in the file).
我不会将它用于大量行号(因为内部循环对文件中的每一行运行了很多次)。
回答by Vicky
You can use a couple of simple batch files:
您可以使用几个简单的批处理文件:
main.bat:
main.bat:
@echo off
set k=0
for /f "tokens=1*" %%i in (%1) do call helper %%i %%j
helper.bat:
helper.bat:
@echo off
for /f %%j in (numbers.txt) do if /I %k% equ %%j echo %1 %2
set /A k=%k%+1
Then supply a numbers.txt file which contains the line numbers you want to print, one per line, and call it as:
然后提供一个 numbers.txt 文件,其中包含要打印的行号,每行一个,并将其命名为:
main.bat my_file.txt
where my_file.txt is the file you want to extract lines from.
其中 my_file.txt 是您要从中提取行的文件。