Home > Net >  Output all results of findstr to seperate txt files
Output all results of findstr to seperate txt files

Time:02-03

Currently my code is: findstr Starfy ./List.txt > result.txt

My result.txt is

3841 - Legendary Starfy, The (USA).zip

x166 - Legendary Starfy, The (USA) (Demo) (Kiosk).zip

However, I want result 1 and result 2 to have their own seperate files, so it would look like:

result1.txt > 3841 - Legendary Starfy, The (USA).zip

result2.txt > x166 - Legendary Starfy, The (USA) (Demo) (Kiosk).zip

I'm unsure how to make this work, and would love if someone is able to help point me in the right direction.

CodePudding user response:

for /f "tokens=1,* delims=:" %%S in ('findstr /i "echo" "%~f0"^|findstr /n /i "echo" ') do ECHO %%T>"U:\moreresults\result%%S.txt"

The command quoted in parentheses finds a string (in this case, echo) ignoring case (/i) within the file "%~f0" (this batch file, which contains a heap of standard code I use for testing). This is passed to another instance of findstr, this time looking for the same string, but numbering the lines (as serialnumber:linetext).

The resultant text is tokenised using : as a separator, so %%S receives the serialnumber and %%T receives the rest of the line (token *). Then simply build the result filename using %%S and write the text part of the line to it.

The caret is used to escape the pipe so that cmd knows that the pipe is part of the command-to-be-executed, not of the for command.

CodePudding user response:

Assuming that you do not already have files in the location you're outputting your results, which could alalready be named using that intended naming scheme, then something like this may suit you:

@Echo Off
SetLocal EnableExtensions EnableDelayedExpansion
Set "i=0"
For /F Delims^=^ EOL^= %%G In (
    '%SystemRoot%\System32\find.exe /I "Starfy" 0^<".\List.txt" 2^>NUL'
) Do (
    Set /A i  = 1
    1>"Result!i!.txt" Echo %%G 
)

Please note that I used find.exe instead of findstr.exe simply because your example used a simple string containing a series of alphabetic only characters. Feel free to change it to '%SystemRoot%\System32\findstr.exe /LIC:"Starfy" ".\List.txt" 2^>NUL', or similar, should you require a more specialized matching mechanism.

  •  Tags:  
  • Related