Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I want to create a batch file which will essentially find a string in a text file, via Findstr for example and also print the line number where the result occurs. Then from the line number result, copy the previous 2 lines of text.
Findstr /N 35=order24 log01.txt
*** Then with the result of the line number I want to copy the 2 line before.
For example say the result I get is
[1001] lofile sfe 37=order24
I want to copy lines 999, 1000, and 1001.
Is this possible? I hope I've given enough information. I'm using XP.

@echo off > newfile & setLocal enableDELAYedexpansion
set N=
for /f "tokens=1 delims=[]" %%a in ('find /n "35=order24" ^< log01.txt') do (
set F=%%a
)
set /a P=!F!-1
set /a PP=!F!-2for /f "tokens=1* delims=[]" %%a in ('find /n /v "" ^< log01.txt') do (
set /a N+=1
if !P! equ !N! >> newfile echo %%b
if !PP! equ !N! >> newfile echo %%b
)
=====================================
Helping others achieve escape felicityM2

Alternatively, use GNU grep for Win32 and do it in one line of code:
type log01.txt | grep -B 2 "35=order24"

>> type log01.txt | grep -B 2 "35=order24"
No need "type". grep takes in an argument, a file.
grep -B 2 "35=order24" log01.txt

@ghostdog: you are correct, but when I tried it, my version of grep appears to have a bug and it doesn't print the matched lines except if you pipe the input into it. It doesn't work with redirection either. grep -V says GNU grep 2.5.4, but it's probably not this version itself but the port, or the run-time library, that is to blame. I don't remember where I got this from, it could be gnuwin32, mingw, cygwin, or something else. I wish GNU utilities would tell you which port, or which compiler and compilation options, they were built with. All they say is their version number, which is not very helpful sometimes.

well, it shouldn't be because i am using GNU grep 2.5.4 as well... and -B works correctly for me. Download grep from GNU .

Aha! Found out the problem. In fact, I was using exactly the version you suggested I download. The problem was that the file I was using as a test, happened to be in Unicode. D'oh!
The cmd.exe TYPE command converts Unicode files to the 8-bit code page you're currently using, which is why grep worked when I piped the output of TYPE to it.

"The cmd.exe TYPE command converts Unicode files to the 8-bit code page you're currently using, which is why grep worked when I piped the output of TYPE to it."
There is one very notable exception to this, unicode files created "cmd /u" on Xp(maybe others as well) don't have the two byte unicode header so type interprets them as text.
cmd /u /c "dir > sometextfile.txt" type sometextfile.txt

Aha
Good detective work, k & J.
Also a cool name for a band. LOL
=====================================
Helping others achieve escape felicityM2

![]() |
![]() |
![]() |
| Login or Register to Reply | |
| Login | Register |
| Ads by Google |