Skip to content

Read files: cat, head and tail

Read whole files with cat, the first lines with head and the last lines of a log with tail -n. Practise on sample files in a terminal in your browser.

Lesson 7 of 166 minSkip to the terminal ↓

cat: the whole file

cat prints a file from top to bottom. It's perfect for short files:

cat recipes/pancakes.txt

cat -n numbers the lines. Give cat several files and it prints them one after another (its name comes from concatenate).

head: the beginning

For a long file, you rarely want all of it. head prints the first 10 lines; -n picks how many:

head poem.txt
head -n 2 poem.txt

tail: the end

tail prints the last 10 lines. Programs add new lines to the end of their log files, so tail is how you see what happened most recently:

tail logs/app.log
tail -n 3 logs/app.log

tail -n +5 does the opposite of what you might guess: it prints everything from line 5 onwards. On a real server, tail -f keeps the file open and prints new lines as they arrive.

To scroll through a long file on a real system, use less (press q to quit). This practice terminal doesn't have it: use head and tail.

Your task

Print the whole pancake recipe with cat, then just the first 3 lines of poem.txt, then just the last 5 lines of logs/app.log.

  • Print recipes/pancakes.txt (not done yet)
  • The first 3 lines of poem.txt (not done yet)
  • The last 5 lines of logs/app.log (not done yet)

Lesson 7 of 16.

learner@sandbox: ~bash (practice)
Note: Practice shell for this lesson. Type a command and press Enter (help lists them all).