Batch extract every nth line

February 22, 2009 at 23:59:52
Specs: Windows XP
I read this thread:

http://www.computing.net/answers/pr...

This provided some clues but I'm stumped and I figure this is something you gurus can do in 2 seconds. What I need is a batch file that can process all of the .txt files in a folder (relative path is OK) and do the following:

Take the 7th line of the text file, then take every 8th line thereafter, and put it in a new text file (per input text file).

So, sample.txt would have something like:

Junk
stuff
a
b
c
d
e
f
g
junky
stuffs
born
in
the
usa
t
u
v
w
x
y
z
!

Should output a sample.modified.txt file that would simply say

e
usa
!

I'm trying to learn this by reading the posts but it seems like I'm getting ahead of myself and should start somewhere more newbie, but I need this ASAP. Any takers? Thanks in advance.

-UM


See More: Batch extract every nth line

Report •


#1
February 23, 2009 at 03:15:26
BEWARE: not tested

@echo off & setlocal
for %%i in (*.txt) do (
  set cnt=1
  set out=%%~dpni
  for /F "delims=" %%j in ('type "%%i"') do (
    call :EXT %%j
  )
)
goto :EOF

:EXT
set /A cnt+=1
if %cnt% neq 8 goto :EOF
set cnt=0
echo.%*>> "%out%-new.txt"
goto :EOF
:: End_Of_Batch


Report •

#2
February 23, 2009 at 03:17:03
You loose any '!' in your file. Such is the price of delayed expansion.
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a  i = 2
FOR /F "delims=" %%a IN (sample.txt) DO @(
  SET /a i = (!i! %% 8^) + 1
  IF !i! == 1 ECHO.%%a
)>>sample.modified.txt

EDIT: VVVVV Well, it's the way I prefer, but on this site I tend to go with the more condensed version.

Report •

#3
February 23, 2009 at 03:22:18
Just for that issue I used the internal subroutine way, to avoid the delayed expansion, as we run under NT/4.0

Report •

Related Solutions

#4
February 23, 2009 at 07:08:05
Hey guys-

I really appreciate your quick responses and efforts so far. I tried both scripts but it looks like they only pull the 8th line one time, instead of *every* 8th line. The desired output is the 7th, then the 15th, 23rd, 31st, 39th, ..., nth. The exclamation point was actually just an example and I will not need them, so delayed expansion is ok. I will try to look into this myself in a few hours, but I have to drive 2 hours to work right now.

-UM


Report •

#5
February 23, 2009 at 10:57:28
I was able to modify IVO's code for my purposes. Here is the final product:

@echo off & setlocal
for %%i in (*.txt) do (
set cnt=1
set out=%%~dpni
for /F "delims=" %%j in ('type "%%i"') do (
call :EXT %%j
)
)
goto :EOF

:EXT
set pass=6
set /A cnt+=1
if %cnt% neq %pass% goto :EOF
set cnt=0
echo.%*>> "%out%-new.txt"
set /A pass+=8
goto :EOF
:: End_Of_Batch

Adding this additional variable and modifications allowed me to cherry-pick the lines I needed. Thanks again all for your help; consider this resolved.


Report •


Ask Question