windowspowershellbatch-filecmdfindstr

Windows CLI use FINDSTR to return only everything after the string


I have my CLI query set to:

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

However I only want the search query to return everything after the query:

80.00

Also if I use wild in the filename it returns the whole file name then the line. I want it again to only return everything after the string and not the filename as I want to pipe the results into a text file.

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

Ideally I run my command and just get the following

120.00
110.00
100.00
90.00
80.00

Ideas on how to do this? PowerShell or CMD is fine. At the moment I am going to put it all into a batch script but a PS script would work.


Solution

  • To get the output of a command, use a for /f loop:

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

    Given, your data is always as your example (line is exactly TOTAL xxx.xx and there is no other TOTAL in the files (may want to use findstr /b))

    (batch-syntax. To use it directly on command line, replace every %%a with %a)

    EDIT a bit more complicated with spaces in the filenames. Do it in two steps: first get the pure data splitting by : ("tokens=2 delims=:" %%a) and in a second for split by space (standard delimiter) ("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 bit more code, but better than messing with the original data (renaming files))