Search code examples
regexbatch-filefilenamesbatch-processingfindstr

Using findstr to pass to a variable


I've got some files I'm running with a batch file that loops through everyone in a directory and dumps certain data into a sql table. I'm adding in a time stamp that I'm passing into a variable and trying to add to the sql table using sqlcmd the only problem is that to add in all relevant columns for that entry, I need to pass the names of the files that are being added to the sql table.

Okay here's the catch... the names being added to the sql table aren't the actual file names but database names that can be found in each of these xml files (close enough to xml). So I know where that is and every single one looks something like this abcdir (rest of the name) where the abcdir is a string that starts every single database.

So I thought I could use the findstr function to get the database name but I have very little experience with regex and I'd like to be able to parse out the tags and be left with just name=abcdir (rest of the name)

** * I didn't think any of my code would really be necessary since I'm just asking questions about a particular command but if thats not the case then let me know and I'll post it* **

EDIT: Okay so each file will have something like this if opened in notepad.

<Name>ABCDir Sample Name</Name>

or

<Name>ABCDir Sample Name2</Name>

and I'd like ABCDir Sample Name to be passed to a batch variable. So I thought to use findstr. I have very little grasp of regex but I've tried using findstr >ABCDir[A-Za-z] \path\filename.ext


Solution

  • As I commented above, findstr (or find) will let you scrape lines containing <Name> from a text file, and for /f "delims=<>" will let you split those lines into substrings. With findstr /n, you're looking for "tokens=3 delims=<>" to get the string between <Name> and </Name>.

    Try this:

    @echo off
    setlocal
    
    set "file=temp.txt"
    
    for /f "tokens=3 delims=<>" %%I in ('findstr /n /i "<Name>" "%file%"') do (
        @echo %%I
    )
    

    I'm using /n with findstr to insert line numbers. The numbers aren't needed, but the switch ensures there's always a token before <Name>. Therefore, the string you want is always tokens=3 regardless of whether the line is indented or not. Otherwise, your string could be token 3 if indented, or token 2 if not. This is easier than trying to determine whether the tags are indented or not.