@ECHO off
cls
REM FieldCount.bat
REM Expected command line: FieldCount.bat -p "Field[0-9]{0,2}_Name" -f "\\server\subdir1\subdir2\Extract.csv" -o "D:\Temp\tmpFieldCount.txt"
REM Created by: Dale Giberson (2019)
REM Usage: I'm releasing this for public use. Feel free to reference, use, modify to your hearts content.  All That I ask is that give credit.

REM Force batch variables to be SET every time, not just the first time
setlocal EnableDelayedExpansion

ECHO Incoming CommandLine:
ECHO 	%0 %*
ECHO 	%~0 %~1 %~2 %~3 %~4 %~5 %~6 %~7 %~8 %~9
ECHO.

REM ECHO.
REM ECHO Parsing the command line ...
ECHO Parsing the commandline parameters for [%~0]:
SET myBatch=%~0
SHIFT

REM set the default parameter values
SET mySource=NOTHING
SET myOutputFile=\tmpFieldCount.txt
SET myPattern=.*
ECHO.
ECHO Parameter defaults set to:
ECHO 	[%%mySource%%]    =[%mySource%]
ECHO 	[%%myPattern%%]   =[%myPattern%]
ECHO 	[%%myOutputFile%%]=[%myOutputFile%]

ECHO.
ECHO Checking parameter list:

:parse
SET parmEmpty=FALSE

REM Break from GOTO loop once reviewed all parameters
IF [%0]==[] GOTO EndParse

REM Give help info to the user
IF ["%~0"]==["?"]     GOTO Help
IF ["%~0"]==["-?"]    GOTO Help
IF ["%~0"]==["/?"]    GOTO Help
IF ["%~0"]==["-h"]    GOTO Help
IF ["%~0"]==["-help"] GOTO Help
IF ["%~0"]==["/help"] GOTO Help

REM Set the filename to examine
IF ["%~0"]==["-f"] (
	IF ["%~1"]==[""]   SET parmEmpty=TRUE
	IF ["%~1"]==["-p"] SET parmEmpty=TRUE
	IF ["%~1"]==["-o"] SET parmEmpty=TRUE
	IF !parmEmpty!==FALSE (
		SET mySource=%~1
		ECHO 	Found [-f] flag ... [%%mySource%%] ....... set to user value of [%~1]
		SHIFT
	) ELSE (
		REM ECHO 	Found [-f] flag ... [%%mySource%%] ....... set to DEFAULT_VALUE of [!mySource!]
		ECHO 	ERROR_FILE_NOT_FOUND ^(0x2^): No source filename deteected in the parameter list
		ECHO.
		ECHO Cannot execute utility without a source file.  Exiting with error.
		EXIT /B 0x2
		GOTO DoNothing
	)
)

REM Set the output file for the data
IF ["%~0"]==["-o"] (
	IF ["%~1"]==[""]   SET parmEmpty=TRUE
	IF ["%~1"]==["-f"] SET parmEmpty=TRUE
	IF ["%~1"]==["-p"] SET parmEmpty=TRUE
	IF !parmEmpty!==FALSE (
		SET myOutputFile=%~1
		ECHO 	Found [-o] flag ... [%%myOutputFile%%] ... set to user value of [%~1]
		SHIFT
	) ELSE (
		ECHO 	Found [-o] flag ... [%%myOutputFile%%] ... set to DEFAULT_VALUE of [!myOutputFile!]
	)
)

REM Set the field pattern to count
IF ["%~0"]==["-p"] (
	IF ["%~1"]==[""]   SET parmEmpty=TRUE
	IF ["%~1"]==["-f"] SET parmEmpty=TRUE
	IF ["%~1"]==["-o"] SET parmEmpty=TRUE
	IF !parmEmpty!==FALSE (
		SET myPattern=%~1
		ECHO 	Found [-p] flag ... [%%myPattern%%] ...... set to user value of [%~1]
		SHIFT
	) ELSE (
		ECHO 	Found [-p] flag ... [%%myPattern%%] ...... set to DEFAULT_VALUE of [!myPattern!]
	)
)

SHIFT
GOTO parse
:EndParse
ECHO.

ECHO Command line parsed as:
REM ECHO 	[%%myBatch%%] = [!myBatch!]
ECHO 	[%%mySource%%]     = [!mySource!]
ECHO 	[%%myPattern%%]    = [!myPattern!]
ECHO 	[%%myOutputFile%%] = [!myOutputFile!]

REM Use a PowerShell command to parse the header line of the file and return the number of fields that match the pattern
set psCommand=powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {((Get-Content -Path '%mySource%' -TotalCount 2)[0] -split ',' -match '%myPattern%').count}"
ECHO.
ECHO PowerShell Command:
ECHO 	%psCommand%

REM GOTO DoNothing

FOR /f "delims=" %%a IN ('%psCommand%') DO @set myFieldCount=%%a

REM @ECHO ON
DEL /s "!myOutputFile!"  >NUL 2>&1
REM @ECHO OFF
REM ECHO.
ECHO FieldCount of "!myPattern!" = !myFieldCount!

REM Writing to output file:
ECHO FieldCount > "!myOutputFile!"
ECHO !myFieldCount! >> "!myOutputFile!"

GOTO DoNothing

:Help
ECHO This utility returns the number of fields in the first row of the given comma delimited text file that matches the regex pattern 
ECHO.
ECHO FieldCount.bat -f [drive:][path][filename] -p pattern -o [drive:][path][filename]
ECHO 	-f [drive:][path]filename
ECHO 			Specifies a file or files to examine
ECHO 			examples: 
ECHO 				-f "..\myFile.csv"                                         ... relative path and  filename
ECHO 				-f "c:\temp\myFile.csv"                                    ... absolute path and filename
ECHO 				-f "\\entsifs1\report\Reference\Lawson Setup\COA_Map1.csv" ... UNC path and filename
ECHO 	-p pattern
ECHO 			Searches the first row of the file using the regular expression pattern
ECHO 			examples: 
ECHO 				-p ""                     ...  Returns a count of all fields
ECHO 				-p "V[0-9]"               ...  Returns a count of all fields like V0, V1, ... ,V9	
ECHO 				-p "Depth[0-9]{0,2}_Sys_Name" ...  Returns a count of all fields like Depth_Name, Depth0_Name, ... ,Depth99_Name
ECHO 			For help see https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285
ECHO 	-o [drive:][path]filename
ECHO 			Specifies the output file to hold the field count for TM1
ECHO 			examples: 
ECHO 				-o "..\myFile.csv"                                         ... relative path and  filename
ECHO 				-o "d:\temp\tmpFieldCount.txt"                             ... absolute path and filename

:DoNothing
EndLocal
