← Learning Hub
Beginner

Reading Files: cat, head, tail, wc

Reading files quickly - config files, CSV data, and especially logs - is a daily task on servers. These commands let you see the start, the end, or live updates of any file without opening an editor.

Example
$ cat products.csv
id,name,category,price
1,Kettle,kitchen,1299
2,Iron,home,899
3,Toaster,kitchen,1599
4,Mixer,kitchen,2499
5,Fan,home,1499
$ head -n 3 products.csv
id,name,category,price
1,Kettle,kitchen,1299
2,Iron,home,899
$ tail -n 2 products.csv
4,Mixer,kitchen,2499
5,Fan,home,1499
$ wc -l products.csv
6 products.csv
  • cat - print the whole file (fine for small files)
  • head -n 3 / tail -n 3 - first or last lines
  • wc -l - count lines (-w words, -c bytes)
  • less file - scroll through a big file (arrows, /word to search, q to quit)

Watching a log live

Example
tail -f logs/access.log      # keeps printing new lines as the server writes them
                             # press Ctrl+C to stop

tail -f is how developers watch what a server is doing right now.

Editing files in the terminal

  • nano file.txt - simple editor. Save with Ctrl+O then Enter, exit with Ctrl+X.
  • vim - powerful but tricky at first. If stuck: press Esc, type :q! and Enter to leave without saving.
Key points
  • cat, head and tail show files.
  • wc counts lines.
  • tail -f follows a log live.

📝 Test yourself

1. Which command shows the last lines of a file?
2. What does tail -f do?
3. Fill in the command that counts lines:
-l products.csv