将命令输出送入 for /f

feed command output into for /f

是否可以将命令输出通过管道传输到以下批处理文件作为其输入?

我想将 dir c:\temp |find "05" |find "new" 等命令的输出提供给以下批处理文件。因为我的命令有很多变化,我不想每次需要时都编辑批处理文件,因此,我正在寻找一种方法将命令输出直接提供给批处理文件,而不是让批处理文件生成它的输入使用 dir /b。基本上,我想要实现的是从文件列表(使用 dir 命令生成)中找到名称包含最高编号的文件(使用批处理文件实现)。示例:

today123.txt
today456.txt
tomorrow123.txt
tomorrow456.txt

通过dir命令,我可以过滤掉今天或明天,只留下两个文件。然后,将这两个文件提供给批处理文件,并使其 select 文件名中包含 456 的文件。当然,这是一个简化的例子。我可能比示例中的文件和组更多。

for /f %%a in ('dir /b ^|sort /r ^|findstr /r [0-9]') do (
  set "filename=%%a"
  goto done
)
:done
echo the highest found is %filename%
exit /b 0

有很多方法。这是其中之一:

@echo off & set filename=
if "%~5" == "" set "myfind=dir /b ^| find "%~2" ^| find "%~3" ^| find "%~4" ^|sort /r ^|findstr /r [0-9]"
if "%~4" == "" set "myfind=dir /b ^| find "%~2" ^| find "%~3" ^|sort /r ^|findstr /r [0-9]"
if "%~3" == "" set "myfind=dir /b ^| find "%~2" ^|sort /r ^|findstr /r [0-9]"
if "%~2" == "" set "myfind=dir /b ^|sort /r ^|findstr /r [0-9]"

pushd "%~1"
for /f %%a in ('%myfind%') do (
  set "filename=%%a"
  goto done
)
:done
popd
if not defined filename echo Not match found & exit /b 1
echo the highest found is %filename%
exit /b 0

通常你会运行它作为:

batch-file-name.cmd "C:\path\to\search" "search1" "search2" "search3"

例如,使用您的示例:

batch-file-name.cmd "c:\temp" "05" "new"

甚至扩展搜索:

batch-file-name.cmd "c:\temp" "05" "new" ".txt"

工作原理: 我们每次都设置搜索字符串,以防需要额外的 find 命令。现在我们最多有三个发现和一条路径,但它可以扩展到更多。不过,您必须按降序设置它们。 我还添加了一个额外的语句 if not defined filename 以确保在发现不匹配时提醒您。

以下获得给定组中最高的:

@echo off
setlocal enabledelayedexpansion
set "search=today"
set "max=0"
for %%a in (%search%*.txt) do (
  set "name=%%~na"
  set "number=!name:%search%=!"
  if !number! gtr !max! set /a max=number
)
echo max number for %search% is %max%
set "highest=%search%%max%.txt"
echo %highest%

注意,根本没有错误检查,所以这取决于文件名的正确格式。 (需要时可以添加错误检查)

要获取搜索字符串作为参数,只需将 set "search=today" 替换为 set "search=%~1"