store nth line of file in variable

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Sponge Belly
Posts: 200
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

store nth line of file in variable

#1 Post by Sponge Belly » 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).

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.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: store nth line of file in variable

#2 Post by Ed Dyreen » 23 Nov 2012 06:25

'
Just a comment...

You can use more /?, more +n for line number.

foxidrive
Expert
Posts: 6033
Joined: 10 Feb 2012 02:20

Re: store nth line of file in variable

#3 Post by foxidrive » 23 Nov 2012 06:32

In the interests of brevity, this puts the Nth line into a variable.

Limitations are that the file has to be less than 64K lines.

Syntax: GetNthLine "file.txt" number

Code: Select all

@echo off
set /a num=%2-1
more +%num% <"%~1" >file.tmp
set /p "var="<file.tmp >nul
echo %var%
del file.tmp
pause

Sponge Belly
Posts: 200
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

Re: store nth line of file in variable

#4 Post by Sponge Belly » 23 Nov 2012 14:16

@Ed and @Mic:

Well, I suppose if we had bigfile.txt and we wanted to isolate the 100th line in its own file, we could try the following from the command line:

Code: Select all

more +99 bigfile.txt | findstr /n $ | findstr /b "1:" ^
| (pause>nul&pause>nul&findstr $ >line100.txt)


Should work with long lines. I'm sure Dave "findstr pathologist" Benham could tell us exactly how long.

If I was feeling energetic, I'd wrap up the above spaghetti in a for loop and capture the output in a variable, but it's hardly worth it efficiency-wise what with a more and 3 findstrs.

@Billrich

Save Foxidrive's snippet to a file called getnthline.cmd. Run it from the command line like this:

Code: Select all

getnthline getnthline.cmd 2


and it should echo the second line of getnth.cmd. There should also now be a variable called var in your parent environment.

But it uses more, set /p, and temporary files. All things I try to avoid if possible.
Last edited by Sponge Belly on 23 Nov 2012 14:34, edited 1 time in total.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: store nth line of file in variable

#5 Post by Ed Dyreen » 23 Nov 2012 14:32

Sponge Belly wrote:Should work with long lines. I'm sure Dave "findstr pathologist" Benham could tell us exactly how long.
Well, according to this article
ss64.com wrote:Line Length limits

Files specified as a command line argument or via the /F:FILE option have no known line length limit. Searches were successfully run against a 128MB file that did not contain a single <LF>.

Piped data and Redirected input is limited to 8191 bytes per line. This limit is a "feature" of FINDSTR. It is not inherent to pipes or redirection. FINDSTR using redirected stdin or piped input will never match any line that is >=8k bytes. Lines >= 8k generate an error message to stderr, but ERRORLEVEL is still 0 if the search string is found in at least one line of at least one file.

Sponge Belly
Posts: 200
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

Re: store nth line of file in variable

#6 Post by Sponge Belly » 23 Nov 2012 14:45

Thanks Ed!

That's what I thought.

Will file that link away for future reference.

Btw, who broke the bad news about more's 64k line limit? Does anyone have a link for that? I like to cite references in my blog posts whenever practicable.

dbenham
Expert
Posts: 2388
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: store nth line of file in variable

#7 Post by dbenham » 23 Nov 2012 19:30

Ed Dyreen wrote:Well, according to this article
ss64.com wrote:Line Length limits

Files specified as a command line argument or via the /F:FILE option have no known line length limit. Searches were successfully run against a 128MB file that did not contain a single <LF>.

Piped data and Redirected input is limited to 8191 bytes per line. This limit is a "feature" of FINDSTR. It is not inherent to pipes or redirection. FINDSTR using redirected stdin or piped input will never match any line that is >=8k bytes. Lines >= 8k generate an error message to stderr, but ERRORLEVEL is still 0 if the search string is found in at least one line of at least one file.


Yep, straight from my SO post. I posted the link on the SS64 Windows CMD shell forum and invited Simon to include the info in his CMD reference docs. He gave me a credit at the bottom :D


Dave Benham

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: store nth line of file in variable

#8 Post by Ed Dyreen » 23 Nov 2012 20:16

dbenham wrote:Yep, straight from my SO post. I posted the link on the SS64 Windows CMD shell forum and invited Simon to include the info in his CMD reference docs. He gave me a credit at the bottom :D
Funny, I thought it was the other way around, that you took it from them. :)
They could have just included your complete post instead of just a snippet with incomplete information.
Can't stop wandering what the freaky deeky you do all day, that requires such thorough knowledge of the findstr.
I automate complete networks with cmd, vbs and au3 yet rarely need the findstr.

Post it here at dosTips, then I can bookmark it ( not a stack overflow fan sorry ) :mrgreen: :lol:

Sponge Belly
Posts: 200
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

Re: store nth line of file in variable

#9 Post by Sponge Belly » 23 Dec 2012 15:33

Hi Again!

I've written a program to copy a line from a text file and save it to a new file. It uses more, findstr, and temporary files to do the heavy lifting so it should work for lines >8191 characters.

I won't include the program here because much of the code is similar to my previous effort. But if you're really curious, you can view this post on my blog.

As always, your feedback is encouraged and greatly appreciated. :-)

Samir
Posts: 362
Joined: 16 Jul 2013 12:00
Location: HSV
Contact:

Re: store nth line of file in variable

#10 Post by Samir » 15 Aug 2020 19:46

I hate to bump an older thread, but this is exactly what I needed to store a line of html into a variable from a file but it doesn't seem to work. :cry:

I'm sure it has to do with the fact that html has all those wonderful < and > that will drive batch batty, but this is my challenge.

Any assistance appreciated.

Sponge Belly
Posts: 200
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

Re: store nth line of file in variable

#11 Post by Sponge Belly » 17 Aug 2020 08:24

Hi Samir! :)

To paraphrase Robbie Robertson, this is sure stirring up some ghosts for me. ;)

Two things spring to mind. What code are you using? And are the HTML files in Unicode format?

TIA!

- SB

Post Reply