first off I haven never really used batch but I'm trying to accomplish something and start to feel overwhelmed. I have a bunch of *txt files in Subdirectories. I want to search these *txt files for if they don't contain a certain string (ABCDEF) and output the results into a new file.
If a file doesn't contain ABCDEF:
output the Filepath and Name as well as the content of every line that begins with "[".
If a file contains ABCDEF one or more times:
Search between lines beginning with "[" for ABCDEF if not found output the first of the two lines beginning with "[" and move like that through the whole file.
Example
My files look like this:
[ID1]
text not containing abcdef
[ID2]
text containing abcdef
[ID3]
text not containing abcdefHere my sample output should be:
Filename
[ID1]
[ID3]
Additional clarification of requirements
I have a bunch of AD User Group Logs in different folders. These are exported at random times and saved as *.txt. These Files contain from just a few up to a few hundred lines and are all set up the same way (as displayed above).
What my idea in terms of pseudocode is, is the following:
Loop through all folders and subfolders
Go through the files file by file
var output
var searchString = abcdef
var currentfile = Current File Name/Path
While nextline != End of File{
If currentline[0] = "["
output = currentline
While nextline[0] != "["
If currentline.contains(searchString)
If currentfile != 0{
echo currentfile
}
echo output
currentfile = 0
break
else
continue
}
So pretty much: look for searchstring, if you find: output the last line before that began with "[" and then keep looking
To add what I have gotten so far: I managed to get the files containing the name and getting the first GUID since it is always the first line.
Sadly /v didn't work since as soon as a line doesn't contain the searchstring it evaluates as true.
Edit I got it so far as I now am able to get all files that don't contain my search string by replacing && with ||. Now if I get it to output all lines beginning with [ in those files I'm halfway there Done.
Now all I have to find is a way to search the blocks between the lines beginning with "[" and return the values if nothing is found. Maybe someone has a tip? ^^
This is my code so far:
@echo off & setlocal
set "SrcDir=my root directory"
set "FileType=txt"
set "SearchKey=abcdef"
set "LogFile=output.log"
set linenum=1
(for /R %%f in ("*.%FileType%") do (
type "%%~f" | findstr /c:"%SearchKey%" > NUL || (
echo %%~f & for /f "delims=" %%a in ('findstr /r /b /c:"\[" "%%~f"') do echo %%a
)
)) > "%LogFile%"