Get the nth line of a text file using Windows Batch Scripting

Written by James McDonald

March 3, 2009

This is something I just made up to parse a csv file and return a specific value from the first content line (line 2) and the last line of the file. The purpose for it was to get that information and then format a new filename of “YYYYMMDD-%FILENAME%-%FIRST%-%LAST%.xls” e.g. “20090303-tags-1062-1357.xls”

@echo off

SET FILE=tags.txt

REM Get the Nth LINE
REM use type to pipe the contents of the file to the next process
REM use findstr to mark the line numbers using /N ".*"
REM use findstr again to find the correct line number e.g "^2:" 
REM format of line is 2:1062,"A Text Description","653426","SomeText","","",-240
REM I am looking for the second token which is 1062 

for /f "usebackq tokens=2 delims=:," %%i in (`type %FILE%  ^| findstr /N ".*" ^| findstr "^%LINE%:"`) do ( SET FIRST=%%i)

REM Get the Last Line
REM just loop through and set LAST until it is the end one.

for /f "usebackq tokens=1 delims=:," %%i in (`type %FILE%`) do ( SET LAST=%%i)

echo "%FIRST%"
echo "%LAST%"

REM This formats a date as YYYYMMDD from the output of echo %DATE%
REM On my system echo %DATE% outputs "Tue 03/03/2009"
for /f "usebackq tokens=2-4 delims=/ " %%i in (`echo %DATE%`) do SET YMD=%%k%%j%%i

echo %YMD%


Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…

How to Research a CPU Upgrade

How to Research a CPU Upgrade

Upgrade Time! Doing a lot of VMWare Workstation virtualization to create labs for self-study and training. Finding...