如何使用 windows 批处理脚本按照显示的顺序从文本文件中读取行?

How do I read lines from a text file in the order presented using windows batch script?

我有一个如下所示的文本文件

number 1
some junk goes here
fruit: apple
number 2
some stuff goes here
fruit: banana
number 3
some stuff goes here
fruit: orange

我的脚本是这样的

@echo off

setlocal EnableDelayedExpansion

set input_file=testfile.txt

for /f "tokens=2" %%a in (
    'findstr " 1 2 3" %input_file%'
) do echo      %%a

for /f "tokens=*" %%b in (
    'findstr "fruit" %input_file%'
) do echo      %%b

我当前的代码给了我这个

1
2
3
fruit: apple
fruit: banana
fruit: orange

如何获得这样的输出格式?

1
fruit: apple
2
fruit: banana
3
fruit: orange

提前致谢。

您发布的示例代码未提供您显示的结果。

我仍然对发布答案持怀疑态度,因为我不是 100% 了解您的实际要求,但我认为,鉴于当前示例,为什么不呢。

@echo off
set "inputfile=testfile.txt"
for /f "tokens=1,2*" %%i in ('type "%inputfile%"') do (
    echo %%j | findstr /RC:"[0-9]"
    echo %%i %%j | findstr "fruit"
)

这可能与您想要的相去甚远,但考虑到当前的示例,这就是我现在可以提供的全部帮助。

这个答案的想法实际上是为了证明我们使用一个循环,而不是两个。您尝试的方式会先创建第一个集合,然后再创建下一个集合,这显然不是您所需要的。

您可以使用 FOR 命令的 tokens 和 delims 选项来发挥您的优势。然后使用 IF 命令确定它正在处理哪一行。

@echo off

set input_file=testfile.txt

for /f "tokens=1* delims= " %%G in ('findstr /RIC:"number [1-9]*" /IC:"fruit:" %input_file%') do (
    IF /I "%%G"=="number" echo %%H
    IF /I "%%G"=="fruit:" echo %%G %%H
)

输出

C:\Users\Squashman\Desktop>so.bat
1
fruit: apple
2
fruit: banana
3
fruit: orange