Search code examples
textfor-loopbatch-file

Getting second line of text set as a variable using FOR in batch


I have a text file on my desktop named "1234.txt" and it contains four lines of text that looks like:

Test
Test1
Test2
Test3

I want to echo the second line (aka Test1) using the FOR command. I am using this:

@echo off
for /f "skip=1" %%G IN (1234.txt) DO @echo %%G
pause

and it returns

Test1
Test2
Test3
Press any key to continue . . .

How do I set up the FOR command to only read that second line (Test1), not the third and fourth as well? Cheers


Solution

  • try this:

    @echo off
    for /f "skip=1" %%G IN (1234.txt) DO if not defined line set "line=%%G"
    echo %line%
    pause
    

    other example:

    for /f "tokens=1*delims=:" %%G in ('findstr /n "^" 1234.txt') do if %%G equ 2 echo %%H