3

How can I print first 5 lines of the file in windows CMD?

There is a problem that I can't use PowerShell (spicific task) and batch scripts. Can you help me with this?

nabrond
  • 1,368
  • 8
  • 17
Jade
  • 283
  • 3
  • 9
  • 18
  • http://stackoverflow.com/questions/1295068/windows-equiv-of-the-head-command – Kent Sep 09 '14 at 14:38
  • more +2 myfile.txt will print everything after the first two lines. - Doesn't work for me. – Jade Sep 09 '14 at 14:40
  • Try this http://stackoverflow.com/questions/155932/how-do-you-loop-through-each-line-in-a-text-file-using-a-windows-batch-file – Raf Sep 09 '14 at 14:48
  • I can't use scripts. I just need to print 5 first lines of the file. That's it... – Jade Sep 09 '14 at 14:49

2 Answers2

6

You should be able to use the more command in some regard.

Maybe "more filename P 5"

see http://support.microsoft.com/kb/227449

tuxy117
  • 160
  • 6
  • 1
    Doesn't work. It prints all lines in file and I need to stop the 'more' process after(this is not allowed). But thanks for your reply – Jade Sep 09 '14 at 14:38
  • 1
    findstr /n "." myfile.txt | findstr "^.:" gives the first 9 lines – tuxy117 Sep 09 '14 at 14:41
  • Okay, that worked. Can you please explain me, what does it mean? – Jade Sep 09 '14 at 14:43
  • But, what if I have log file with size 10 GB? It will take a huge amount of time... – Jade Sep 09 '14 at 14:48
  • the /n after the first findstr prints out the line numbers so using only that first part would print out the entire file with line numbers. The second findstr limits the lines printed to single digit numbers (since the line number is printed out every line takes the form ".:" with it's first two characters). It's a bit hacky but I dunno how else you would go about doing this – tuxy117 Sep 09 '14 at 14:48
  • I tried it on the logfile 2 GB. And it took about of 2 mins. It is very greedy, so I can't use this. But many thanks for your reply – Jade Sep 09 '14 at 14:52
  • 1
    Yeahhh unfortunately it parses through the entire file – tuxy117 Sep 09 '14 at 14:54
  • 1
    How come this has been marked as the answer? The given solution prints all lines – Zimba Jun 22 '21 at 16:19
4

Alright, it might be like replying to a very old thread, but still for anyone who would benefit from this.
Use findstr

findstr /n . yourfile.txt  | findstr "^[0-5]:"

The breakdown is-
first findstr prints the line number where it finds any character (denoted by a literal dot), second findstr will print lines that start ( using ^ for this ) with any number ranging from 0 through 5. Also include ":" there to avoid findstr matching with recurring digits like 12,13,14... 21,22,23..., etc.
^[0-5]: will match only for lines starting with-

1:
2:
3:
4:
5:

I tested it on a 250 MB file and it worked within a second.

The same can be achieved in linux using sed-

sed -n '1,5p' yourfile.txt
nav33n
  • 113
  • 9