Command line tip - peek into the start and end of files

Sometimes, especially when dealing with log files, you might want to peek at the start and/or end of a file to see just that bit of the file and not the whole thing. Of course, there are a couple of easy commands that allow you to do this.

The commands are head and tail and work with almost any Unix-like operating system.

As the name suggests, head is for peaking at the top of a file. By default, it will show you the first 8 lines of the file:

$ head /path/to/file

You can override the number of lines displayed with the -n switch:

$ head -n 10 /path/to/file

In this example, we'll return the first 10 lines of the file.

Funnily enough, tail is exactly the same, but works for the end of the file. Our two examples again:

$ tail /path/to/file

For a set number of lines (counting back from the last line), use -n again:

$ tail -n 10 /path/to/file

A very simple, but effective and useful command line tip!

Avatar for peter Peter Upfold - http://peter.upfold.org.uk/

Peter Upfold is a technology enthusiast from the UK. Peter’s interest in Linux stems back to 2003, when curiosity got the better of him and he began using SUSE 9.0. Now he runs Linux Mint 9 on the desktop, runs a CentOS-based web server from home for his personal website and dabbles in all sorts of technology things across the Windows, Mac and open source worlds.

Home » Articles »

Discussion: Command line tip - peek into the start and end of files

  1. # Posted on 02 July 2007 at 12:33 PM

    [...] Link to Article linux Command line tip - peek into the start and end of files » Posted at [...]



  2. Gerardo Meléndez (guest)

    # Posted on 02 July 2007 at 10:22 PM

    To see the end of a growing file (for example, a log) the -f switch is usefull because it shows the lines added to the file when te command is running

    tail -f /path/to/logfile

    Then you need control-C to quit.

    Also to see lines 21 to 30 (like MySQL's LIMIT 20,10) you can use:

    head -n 30 file | tail -n 10 # and then head -n 40 file | tail -n 10 # and so on...



  3. Peter (guest)

    # Posted on 03 July 2007 at 12:52 AM

    Thanks Gerardo - awesome addition to the tip!



Home » Articles » Command line tip - peek into the start and end of files