Page 1 of 1

Get Text in Cetrain Lines?

Posted: 07 Apr 2012 05:35
by tinfanide
words.txt
first
second
third
forth
fifth
sixth

Code: Select all

@ECHO OFF

SET "line=5"


CALL :GetLine %line%

PAUSE
GOTO :EOF

:GetLine
SETLOCAL ENABLEDELAYEDEXPANSION

SET /A c=0
FOR /F "tokens=1" %%A IN (words.txt) DO (
   SET /A c+=1
   IF !c!==%1 (
      ECHO %%A
      ENDLOCAL
      GOTO :EOF
      )
)


Is there a simpler way in DOS Commands to get texts in a certain line?
I've thought of the use of skip or MORE, to the best I know, but
they start the first line starting from a certain line.
That lists the rest of texts (not just one line).

Re: Get Text in Cetrain Lines?

Posted: 07 Apr 2012 05:53
by Ed Dyreen
'

Code: Select all

@echo off &setlocal enableDelayedExpansion

set "$file=words.txt"
set  "$row=4" %=   more uses a 0-based index   =%
::
set "$line=" &for /f "delims=" %%? in (

   '^< "!$file!" more +!$row!'

) do    if not defined $line set "$line=%%~?"

echo.$line=!$line!_

pause
exit /b 0

Code: Select all

$line=fifth_
Druk op een toets om door te gaan. . .
This processes simple lines only, to catch complex chars, additional coding is required :!:

Re: Get Text in Cetrain Lines?

Posted: 07 Apr 2012 06:36
by !k

Code: Select all

@echo off &setlocal enableextensions

set /a line=5

call :GetLine %line% words.txt
echo line=%$%.

pause
goto :eof

:GetLine
set /a line-=1
for /f "tokens=1" %%a in ('more +%line% %2') do (
   set "$=%%a" &goto :eof
)

Re: Get Text in Cetrain Lines?

Posted: 07 Apr 2012 07:13
by foxidrive
SED can also be used.


Code: Select all

@echo off
for /f %%a in ('sed -n 5p "file.txt"') do set var=%%a

Re: Get Text in Cetrain Lines?

Posted: 07 Apr 2012 09:09
by tinfanide
Yes, thanks for your examples.
This teaches me more about how to make use of MORE.
I used to be unable to make use of MORE because it lists the rest of the lines starting from +_LineNumber.
But with the SET var=,
it's possible to extract only that line
much like the use of "break" in the JS For Loop.

Re: Get Text in Cetrain Lines?

Posted: 07 Apr 2012 13:59
by Aacini

Code: Select all

@echo off
set line=5
call :GetLine %line%
pause
goto :EOF

:GetLine
set /A skip=%1-1
if %skip% gtr 0 (
   set skip=skip=%skip%
) else (
   set skip=
)
for /F "%skip% delims=" %%a in (words.txt) do (
   echo %%a
   exit /B
)

Re: Get Text in Cetrain Lines?

Posted: 07 Apr 2012 19:32
by tinfanide
Aacini wrote:

Code: Select all

@echo off
set line=5
call :GetLine %line%
pause
goto :EOF

:GetLine
set /A skip=%1-1
if %skip% gtr 0 (
   set skip=skip=%skip%
) else (
   set skip=
)
for /F "%skip% delims=" %%a in (words.txt) do (
   echo %%a
   exit /B
)


Yes, they can be all done by skip, MORE or setting a counter.
Thanks a lot. :D