Head and Tail
Head shows the first lines of a file. Tail shows the last lines of the same file.
First two lines
Head with -n 2 prints the first two lines only.
$ cd ~/practice
$ head -n 2 projects/report.txtLast two lines
Tail with -n 2 prints the last two lines only.
$ cd ~/practice
$ tail -n 2 projects/report.txtFirst three log lines
Head works the same way on the log file.
$ cd ~/practice
$ head -n 3 data/logs.txtThe last number
Tail with -n 1 prints only the final line.
$ cd ~/practice
$ tail -n 1 data/numbers.txtExample
$ cd ~/practice
$ head -n 2 data/numbers.txt
$ tail -n 2 data/numbers.txtKey points
- Use head to see how a file starts.
- Use tail to see how a file ends.
- Head and tail show ten lines when no count is given.
- The -n option sets how many lines to show.
- Use tail on a log file to see its newest lines.
- Head and tail read a file without changing it.
In this example, head prints the first two numbers, 5 and 3. Then tail prints the last two numbers, 1 and 5. The two commands show opposite ends of the same file.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which command shows the last two lines of report.txt?