Shell Head and Tail
Head prints the first lines of a file, and tail prints the last lines. Both commands read from the ends of a file, not the middle.
Print the first lines
notes.txt has four lines, so head prints all four.
head notes.txtPrint the first two lines
head -n 2 prints only the first two lines.
head -n 2 notes.txtPrint the last two lines
tail -n 2 prints only the last two lines.
tail -n 2 notes.txtFirst and last lines of a table
head -n 1 prints the header, and tail -n 1 prints the last row.
head -n 1 data.csv
tail -n 1 data.csvExample
head -n 1 report.txt
tail -n 1 report.txtKey points
- head: a command that prints the first lines of a file.
- tail: a command that prints the last lines of a file.
- Use -n to set how many lines head or tail prints.
- head and tail print ten lines when no number is given.
In this example, head -n 1 prints the first line of report.txt. Then tail -n 1 prints the last line, so the two ends of the file are shown.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which command prints the last three lines of notes.txt?