Viewing Text Files
cat, less, head, tail, wc — reading and measuring files from the command line
Skills taught: linux.cat, linux.less, linux.head, linux.tail, linux.wc
cat, less, head, tail
# cat: print entire file to screen (best for small files)
cat README.md
cat file1.txt file2.txt # concatenate multiple files
cat -n README.md # show line numbers
# less: paginated viewer (best for large files)
less /var/log/syslog
# Navigation in less:
# Space / f = next page
# b = previous page
# g / G = go to start / end
# /search = search forward
# n / N = next / prev search match
# q = quit
# head: first N lines (default: 10)
head config.yml # first 10 lines
head -n 20 config.yml # first 20 lines
head -20 config.yml # same thing
# tail: last N lines (default: 10)
tail server.log # last 10 lines
tail -n 50 server.log # last 50 lines
tail -f server.log # -f: follow (live updates — great for logs!)
tail -f /var/log/nginx/access.log # watch live web traffic
wc — word/line/character count
wc README.md # lines words bytes filename
# → 42 318 2048 README.md
wc -l README.md # line count only: 42
wc -w essay.txt # word count only: 1284
wc -c binary.dat # byte count: 4096
# Count lines in multiple files
wc -l *.js
# → 120 index.js
# → 85 utils.js
# → 205 total
# Count all source files' lines
find . -name '*.py' | xargs wc -l | tail -1 # total lines of Python
Tip: tail -f is indispensable for debugging. It follows a log file in real-time, printing new lines as they are written. Use tail -f /var/log/nginx/error.log while testing your app to see errors as they happen. Ctrl+C to stop following.
Frequently Asked Questions
What is the difference between cat and less?
cat prints the entire file to the terminal at once — fine for small files, but large files will flood the screen. less shows one page at a time and lets you scroll and search. Always use less for files larger than a few screens. less is a pager: its name is a pun on 'more' (the older pager tool).