| Read File Contents [first line or all lines].cmd |
Note that the "FOR" command supports the "skip" option allowing you to skip any expected (irrelevant) header lines you don't wish to process.
| The Code for: "Read File Contents [first line or all lines].cmd" |
This is the example, a shortcut was installed to this code :
@echo off ::echo on ::@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ :: $Header: C:/DBAREIS/Projects.PVCS/Win32/ScriptingTipsAndTricks/EXAMPLE[cmd].Read File Contents [first line or all lines].cmd.pvcs 1.0 11 Jul 2014 19:31:02 USER "Dennis" $ ::@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ setlocal ::--- Create a file containing 10 lines ------------------------------------- set SomeFile=%TEMP%\Has TEN Lines.txt del "%SomeFile%" >nul 2>&1 for /L %%i in (1,1,10) do echo This is line #%%i of 10 >> "%SomeFile%" echo We will read this file echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ type "%SomeFile%" echo ----------[ END OF FILE ]---------- ::--- Read the first line (can use "SET /P" for that) ----------------------- echo.&echo. echo Reading the first line (only): set /P FirstLine=<"%SomeFile%" echo * 1st Line: %FirstLine% ::--- Process the whole file ------------------------------------------------ echo.&echo. set FileLineCnt=0 for /F "usebackq delims=" %%d in ("%SomeFile%") do call :HandleFileLine "%%d" echo Found %FileLineCnt% Lines goto :EOF ::=========================================================================== :HandleFileLine :: Not the processing didn't need to call a separate routine but it makes it :: clearer and easier to code as you don't need to use any "delayed explansion". :: Conditional logic is also much simpler. ::=========================================================================== set FileLine=%~1 set /a FileLineCnt=FileLineCnt + 1 echo [LINE #%FileLineCnt%] %FileLine% goto :EOF
Please note that that I am not trying to show how great I am by producing batch files 9,000 characters long on one line that no one will understand or be able to debug when they go wrong. I am going out of my way to comment the code and make it verbose so beginners and advanced users will both benefit. I don't claim to be an expert that knows everything, if I'm wrong or make a mistake then please contact me and let me know :-)
![]() | ![]() |