head and tail

November 1st, 2006 toydi Posted in head, tail, Text Manipulation | Hits: 161516 | 11 Comments »

Given a list of text lines in a file, to display the first 10 lines:

head foo.txt

To display the last 10 lines:

tail foo.txt

Try -n option to specify the number of lines to display:

tail -n3 foo.txt  # the last 3 lines
head -n4 foo.txt  # the first 4 lines 

And don’t forget, the '+' in tail and '-' in head:

tail -n+10 foo.txt  # start from the 10th line til the last
head -n-10 foo.txt  # print all, except the last 10 lines 

Updates: Inspired by mysurface’s comment, to display the file from 4th line to to 10th line:

head -n10 foo.txt | tail -n+4  # 4th line to 10th line

11 Responses to “head and tail”

  1. head and tail can be combined to create a combo, let say I wanna print a file from line 6 to line 10, I can do this:

    head -n10 foo.txt | tail -n5 

    To indicate that i extract the correct line, i can do this.

    head -n10 foo.txt | nl | tail -n5 

    Place a command to print the line number nl in between the head and tail.

  2. Hi,
    i am working on Solaris9, i want to display the lines satring from 4th line to until last but three lines from the particular line in single shot, example liek i have 10 lines file and i want display from 4th to 7th lines (but number of lines are not pixed in the file-it will be different number-always number records will be different in my file)

    please help me on this, thanks in advance…!:)


  3. Hi
    i got it ………!
    n=`wc -l test.txt`
    head -(n-3)test.txt|tail -(n-6) >test_result.txt


  4. A useful tip, thanks!

  5. I really like coming to your site. Thank you for this post, since it has been quite interesting. I have a site where I have several music industry jobs available for searching, and would love to link to your website.

  6. You could definitely see your enthusiasm within the work you
    write. The world hopes for even more passionate writers
    like you who aren’t afraid to mention how they believe.
    At all times go after your heart.

  7. hey there!

    How to see the middle of any text?
    with what command

  8. Even from the home environment more and more cleaning agents, solvents, detergents, oils and also other
    materials potentially harmful to skin are typically available.
    Stress, soap, certain chemicals, animal dander or maybe
    household cleaners may cause a flare-up. Soaking in colloidal
    oatmeal bath is the one other excellent method to relieve the itching.

  9. Hardik patel Says:

    how can i get first 5 line and last 5 line?? using single command

  10. head -n 5 ; tail -n 5

  11. selvanayaki Says:

    How to get first 10 lines of a file using tail command?

Leave a Reply