Windows CLI 使用 FINDSTR 来 return 仅字符串之后的所有内容

Windows CLI use FINDSTR to return only everything after the string

我将 CLI 查询设置为:

c:\>findstr /c:"TOTAL" Invoice.txt 
TOTAL 80:00

但是我只希望搜索查询 return 查询之后的所有内容:

80.00

此外,如果我在文件名中使用 wild,它 return 是整个文件名,然后是行。我再次希望它仅 return 字符串之后的所有内容而不是文件名,因为我想将结果通过管道传输到文本文件中。

c:\>findstr /c:"TOTAL" *.txt
Invoice - Copy (2).txt:TOTAL 120.00
Invoice - Copy (3).txt:TOTAL 110.00
Invoice - Copy (4).txt:TOTAL 100.00
Invoice - Copy.txt:TOTAL 90.00
Invoice.txt:TOTAL 80.00

理想情况下,我 运行 我的命令只得到以下内容

120.00
110.00
100.00
90.00
80.00

关于如何做到这一点的想法? Powershell 或 CMD 都可以。目前我打算将其全部放入批处理脚本中,但 ps 脚本可以工作。

谢谢!

要获取命令的输出,请使用 for /f 循环:

for /f "tokens=2" %%a in ('findstr /c:"TOTAL" *.txt') do echo %%a

鉴于,你的数据总是作为你的例子(行正好是TOTAL xxx.xx并且文件中没有其他TOTAL(可能要使用findstr /b))

(批处理语法。要直接在命令行上使用它,请将每个 %%a 替换为 %a

EDIT 有点复杂,文件名中有 spaces。分两步进行:首先将纯数据按 : ("tokens=2 delims=:" %%a) 拆分,然后 for 按 space (标准分隔符)拆分 ("tokens=2" %%b) :

for /f "tokens=2 delims=:" %%a in ('findstr "TOTAL" *.txt') do (
  for /f "tokens=2" %%b in ("%%a") do echo %%b
)

(代码有点多,但总比弄乱原始数据(重命名文件)好)

A for /F loop can capture the output of the findstr command line. After having stored each line in an environment variable, sub-string replacement 的应用方式包括 : + TOTAL + SPACE被移除:

setlocal EnableDelayedExpansion
for /F "delims=" %%L in ('findstr /C:"TOTAL" "*.txt"') do (
    set "LINE=%%L"
    echo(!LINE:*:TOTAL =!
)
endlocal

只是我的 2 美分 ;-) 。第一个 for 可以很简单,只是迭代文件名。

@Echo off
( For %%A in (*.txt
  ) Do For /f "tokens=2" %%B in ('findstr /B /C:"TOTAL" "%%A"'
  ) Do Echo:%%B
) >All-Totals.txt

在 PowerShell 中也很容易。

PS C:\src\t> Get-Content .\Invoice.txt | Where-Object { $_ -match '.*TOTAL (.*)' } | % { $matches[1] }
120.00
110.00
100.00
90.00
80.00

PS C:\src\t> cat .\Invoice.txt | where { $_ -match '.*TOTAL (.*)' } | % { $matches[1] }
120.00
110.00
100.00
90.00
80.00