Page 1 of 1

Findstr to read user-defined line from a "for" loop

Posted: 15 Jan 2012 01:29
by Rileyh
SCENARIO:
(in test.txt)

Code: Select all

(empty line)
printline Hello World
(empty line)


(in my current batch file)

Code: Select all

@echo off
setlocal enabledelayedexpansion
:loop
set "$file=test.txt"
for /f "tokens=1-2*" %%a in ('findstr /b /i "printline" "!$file!"') do (
  set command=%%a
  set value=%%b
  echo %%b
  goto :break
  )

:break
(file continues)


THE ISSUE:
After extensive trial and error I have concluded that findstr does not read only the first line, it "picks out" the string from the file test.txt rather than reading line by line.
I need it to read the file on a line that I set (as a variable).

Thanks in advance.
Regards,
Rileyh

Re: Findstr to read user-defined line from a "for" loop

Posted: 15 Jan 2012 07:40
by dbenham
:shock: I already answered your identical question at Specify which line to read in "Findstr"
dbenham wrote:

Code: Select all

@echo off
set "$file=test.txt"
set "x=50"
set "command="
set "value="
for /f "tokens=1,2* delims=: " %%a in ('findstr /n /i /b "printline " ^| findstr /b "%x%:"') do (
  set "command=%%b"
  set "value=%%c"
  setlocal enabledelayedexpansion
  echo !value!
  endlocal
)
(file continues)



2 tweaks - no need to keep 1st token, and removed <space> after "printline".

Code: Select all

@echo off
set "$file=test.txt"
set "x=50"
set "command="
set "value="
for /f "tokens=2* delims=: " %%a in ('findstr /n /i /b "printline" ^| findstr /b "%x%:"') do (
  set "command=%%a"
  set "value=%%b"
  setlocal enabledelayedexpansion
  echo !value!
  endlocal
)
(file continues)

Rileyh wrote:After extensive trial and error I have concluded that findstr does not read only the first line, it "picks out" the string from the file test.txt rather than reading line by line.
I need it to read the file on a line that I set (as a variable).

FINDSTR reads every line of test.txt and prints only the lines that match the specified search. That behavior cannot be changed.


Dave Benham

Re: Findstr to read user-defined line from a "for" loop

Posted: 15 Jan 2012 23:32
by Rileyh
I sincerely apologize to both Squashman and dbenham for my poor conduct on this forum. I did not test your code enough dbenham which I have now found out works exactly as I needed it to. I honestly am sorry to you both and I hope that we can get past this.

Apologies,
Rileyh