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.
cat: the whole file
cat prints a file from top to bottom. It's perfect for short files:
cat recipes/pancakes.txtcat -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.txthead -n 2 poem.txttail: 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.logtail -n 3 logs/app.logtail -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.
Tip: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 turn
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.
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)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
cat- Print the contents of files More on cat →
head- Print the first lines of files More on head →
tail- Print the last lines of files More on tail →