Batchfile to create small file of first few lines

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Celia Wang
Posts: 1
Joined: 06 Sep 2015 12:20

Batchfile to create small file of first few lines

#1 Post by Celia Wang » 06 Sep 2015 12:27

I am practicing for GRE and like to memorize/review few GRE words every hour or so for the verbal ability test.

I want to write a batchfile called select.bat that selects 'n' lines from source.txt and writes the 'n' lines in a new file with a random filename. Then, the 'n' lines are removed from the top of source.txt and appended to the bottom of source.txt.

For example, if I use "select.bat 16" I would like my batch file to select the top 16 lines from source.txt into a 'random_name.txt' or 'yyyymmdd-hhmmss.txt' Then, my source.txt should have the top 16 lines removed and stuck to the bottom (as in a computer science "queue.")

Could you please help with such a batch file? Thanks, thank you very much.

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Batchfile to create small file of first few lines

#2 Post by Aacini » 07 Sep 2015 18:55

This is untested:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "N=%~1"
if not defined N echo Usage: %~NX0 numLines & goto :EOF

rem Get the name of random file
set "rand=%random%"

rem Read lines from source.txt file
< source.txt (

   rem Read the top N lines and write they into File%random%.txt
   (for /L %%i in (1,1,%N%) do (
      set "line="
      set /P line=
      echo(!line!
   )) > File%rand%.txt

   rem Copy the rest of lines into source.new
   findstr "^" > source.new
)

rem Add the extracted (first N) lines and append they to bottom of source.new
type File%rand%.txt >> source.new

rem Remove old source.txt and place source.new in its place
move /Y source.new source.txt

Antonio

Post Reply