store nth line of file in variable
Posted: 23 Nov 2012 06:18
Hello All!
A little program that accepts a line number, a filename, and an optional variable name from the command line and stores the contents of the line from the file in the variable (uses NTHLINE if none specified).
For further explanation and discussion, see this post on my blog.
Any comments/feedback appreciated.
A little program that accepts a line number, a filename, and an optional variable name from the command line and stores the contents of the line from the file in the variable (uses NTHLINE if none specified).
Code: Select all
@echo off & setlocal enableextensions
set "a2z=abcdefghijklmnopqrstuvwxyz" & set "nos=0123456789"
if "%~1"=="" (goto usage) else set "nth=%~1"
if "%~2"=="" (set "errmsg=specify a file name" & goto error
) else set "file=%~2"
if "%~3"=="" (set "var=nthline") else (
echo("%~3"| findstr /ix ^"\"[%a2z%][%a2z%_%nos%]*\"^" >nul ^
&& set "var=%~3" || (set errmsg=^""%~3" is invalid variable name^"
goto error))
for /f "tokens=1* delims=0123456789" %%a in ("A0%nth%") ^
do if "%%b" neq "" (
set errmsg=^""%nth%" is not a valid line number^"
goto error)
if %nth%==0 set /a nth=1
if exist "%file%\" (set errmsg=^""%file%" is a folder^"
goto error) else if not exist "%file%" (
set "errmsg=file "%file%" not found" & goto error)
echo("%file%" | findstr "\* \?" >nul ^
&& (set "errmsg=wildcards (* and ?) not permitted in filename"
goto error)
for /f "tokens=1" %%c in ('type "%file%" ^| find /c /v ""') ^
do set /a lines=%%c
if %lines%==0 (set errmsg=^""%file%" is an empty file^"
goto error)
if %nth% gtr %lines% (
set "errmsg=specify a line number between 1 and %lines%"
goto error)
goto loop
:usage
(echo(Stores the nth line of a text file in a variable. & echo(
echo(Usage: & echo(
echo( %~n0 N FileName [Var] & echo(
echo(where the contents of line number N of file FileName ^
will be stored in variable& echo(Var. The variable name ^
NthLine is used by default if none is specified.) 1>&2
:error
if defined errmsg ^
for /f "delims=" %%e in ("%errmsg%") do echo(%%~e 1>&2
endlocal & exit /b 1
:loop
set /a nth-=1
if %nth% gtr 0 set "opts=skip=%nth% "
for /f "%opts%delims=" %%a in ('findstr /n "^" "%file%"') do (
set "line=%%a"
setlocal enabledelayedexpansion
set "line="!line:*:=!""
for /f "delims=" %%b in ("!line!") do (
endlocal & endlocal & set "%var%=%%~b")
if defined %var% (set %var% & exit /b 0
) else (echo(line %~1 of file "%~2" is blank: ^
variable "%var%" not defined 1>&2 & exit /b 1)
)
For further explanation and discussion, see this post on my blog.
Any comments/feedback appreciated.