Reputation: 41
I have a text file, where i have to read line 21 and set it in a variable. Im using the below.
Set Source="C\Users\file.txt"
for /f "Tokens=* delims=" %%G in ('findstr /n "^" %Source%') do (
if %%G equ 21 (
set Variable="%%H"
)
)
Its not working. Please Help.
Upvotes: 1
Views: 674
Reputation: 41
for /f "Tokens=1* delims=:" %%G in ('findstr /n "^" %Source%') do if %%G equ 21 set Variable=%%H
echo.%Variable%
This has my required output.
Upvotes: 0
Reputation: 34899
Given that line 21 is not empty, you could do it like this:
set "SOURCE=C\Users\file.txt"
for /F usebackq^ skip^=20^ delims^=^ eol^= %%L in ("%SOURCE%") do (
if not defined LINE set "LINE=%%L"
)
echo(Line 21 contains "%LINE%".
If line 21 might be empty, you could use this instead:
set "SOURCE=C\Users\file.txt"
for /F "usebackq skip=20 delims=" %%L in ('findstr /N "^" "%SOURCE%"') do (
set "LINE=%%L"
goto :CONTINUE
)
:CONTINUE
set "LINE=%LINE:*:=%"
echo(Line 21 contains "%LINE%".
And here is an alternative approach, using input redirection <
:
set "SOURCE=C\Users\file.txt"
< "%SOURCE%" (
for /L %%I in (1,1,20) do set /P LINE=""
set "LINE="
set /P LINE=""
)
echo(Line 21 contains "%LINE%".
Upvotes: 2
Reputation: 2229
Use SETX with its /A option. See SETX /? for more info.
Okay:
for /f "tokens=*" %V in ('%SystemRoot%\System32\findstr.exe /n /r /c:".*" <FILE_PATH> ^| %SystemRoot%\System32\findstr /b /l /c:"21:"') do set LINE=%V
set LINE=%LINE:~3%
%V needs changing to %%V if used in a script.
Upvotes: -1