如何从cmd命令输出中获取第一行?

Sér*_*nça 0 windows cmd.exe

我只需要从 Windows cmd 命令中获取第一行。

命令示例:

dir /b /o-d cert*.pem
Run Code Online (Sandbox Code Playgroud)

它返回:

cert1.pem
cert2.pem
cert3.pem
Run Code Online (Sandbox Code Playgroud)

如何让第一行返回cert1.pem

操作系统:Windows 10

Nar*_*ard 7

这应该可以做到:

dir /b /o-d cert*.pem > temp.txt && for /l %l in (1,1,1) do @for /f "tokens=1,2* delims=:" %a in ('findstr /n /r "^" temp.txt ^| findstr /r "^%l:"') do @echo %b
Run Code Online (Sandbox Code Playgroud)

中的奖励:

Get-ChildItem hello*.txt | select -first 1
Run Code Online (Sandbox Code Playgroud)


phu*_*clv 5

批量只需要 2 条短线

@echo off

for /f "tokens=* usebackq" %%f in (`dir /b /o:d`) do (set "file=%%f" & goto :next)
:next

echo %file%
Run Code Online (Sandbox Code Playgroud)

结果存储在 %file%

但是,这是一个XY 问题,因为您实际上并不需要获取第一。只需反转排序顺序 ( o:dto o:-d) 并获得最后一行,这可以通过简单的单行轻松完成

@for /f "tokens=* usebackq" %%f in (`dir /b /o:-d`) do @set "file=%%f"
Run Code Online (Sandbox Code Playgroud)