Find and parse folders and files with tree and Findstr windows command.

This tutorial is about the greatest commands and useful under Windows OS.
If you know the grep command from Linux and something about using regular expressions then will be easier.
This link is about Findstr and this link is about Tree command.
The base of this tutorial is how to deal with these commands.
The first step is understanding how is working.
First, the tree command will make on screen the structure of a path.
Next command Findstr will make the searches for patterns of text in files using regular expressions.
About regular expressions then you may know is hard to understanding well, because come with many patents but will show you how to make it.
The base of the command I make it will be this:
tree /f /a | findstr /ri /c:
This will get the output of the tree and will parse with these options: /ri /c: .
/r : Uses search strings as regular expressions. Findstr interprets all metacharacters as regular expressions unless you use /l.
/i : Specifies that the search is not to be case-sensitive.
/c: string : Uses specified text as a literal search string.

The next step is to use the string for regular expressions by adding after /c: this “”.
For example, I will use my Python27 folder to test it with this command:
C:\Python27>tree /f /a | findstr /ri /c:"python"
| python.exe
| python27.dll
| pythonw.exe
| tutoriale_python.txt
| python278.chm
| Python-ast.h
| Python.h
| pythonrun.h
| |
| | | python.gif
| | |
| | | pythoncom.pyc

You can see the output of the tree is parsed and the result is anything has the string: python.
You can parse all output of tree command with the regex pattern is expressed in bytes, like:
tree /f /a | findstr /ri /c:"[a-zA-Z0-9_]"
Another example is to find all executable files into the folder:
tree /f /a | findstr /ri /c:"\.exe$"
I used this to see what python files come with python modules I need:
C:\Python27>tree /f /a | findstr /ri /c:"import sys" /c:"import os" *.py os.path sys os sys

All rules about regular expression can be found here- Regular expression operations.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.