【问题标题】:Windows CLI use FINDSTR to return only everything after the stringWindows CLI 使用 FINDSTR 仅返回字符串之后的所有内容
【发布时间】:2017-11-03 11:34:37
【问题描述】:

我的 CLI 查询设置为:

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

但是我只希望搜索查询在查询后返回所有内容:

80.00

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

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 脚本可以工作。

谢谢!

【问题讨论】:

    标签: windows powershell batch-file cmd findstr


    【解决方案1】:

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

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

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

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

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

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

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

    【讨论】:

    • 很接近但不完全在那里,我必须先删除文件名中的空格 stackoverflow.com/questions/11270453/… 然后你的 for /f 循环才起作用。
    • 对不起,我错过了文件名中的空格。请查看我的编辑。
    【解决方案2】:

    for /F loop 可以捕获findstr 命令行的输出。将每一行存储在环境变量中后,sub-string replacement 可以以一种方式应用,包括 : + TOTAL + SPACE 在内的所有内容都将被删除:

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

    【讨论】:

      【解决方案3】:

      只是我的 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
      

      【讨论】:

        【解决方案4】:

        在 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-19
          • 2012-08-29
          • 2020-01-06
          • 2022-11-30
          相关资源
          最近更新 更多