Linux and Bash course menu
Reading Files in Linux: cat, less, head, tail and wc
View files in the terminal with cat, less, head and tail, follow logs live with tail -f, count lines with wc, compare files with diff, and identify file types.
On this page
We use a small log file, app.log, in this lesson.
cat#
cat prints a whole file. Use it for short files:
cat app.log2026-11-05 09:00 INFO Server started
2026-11-05 09:01 INFO User asha logged in
2026-11-05 09:02 WARN Disk 80 percent full
2026-11-05 09:03 INFO User ravi logged in
2026-11-05 09:04 ERROR Payment failed
2026-11-05 09:05 INFO Report created
2026-11-05 09:06 ERROR Database timeout
2026-11-05 09:07 INFO User asha logged outcat -n adds line numbers:
cat -n app.log | head -n 2 1 2026-11-05 09:00 INFO Server started
2 2026-11-05 09:01 INFO User asha logged inless#
For long files, use less. It lets you scroll without loading everything at once:
less /var/log/sysloghead and tail#
head shows the first lines, and tail the last. Both default to 10 lines:
head -n 2 app.log
echo ---
tail -n 2 app.log2026-11-05 09:00 INFO Server started
2026-11-05 09:01 INFO User asha logged in
---
2026-11-05 09:06 ERROR Database timeout
2026-11-05 09:07 INFO User asha logged outtail -n +7 starts from line 7 to the end, which is useful for skipping a header:
tail -n +7 app.log2026-11-05 09:06 ERROR Database timeout
2026-11-05 09:07 INFO User asha logged outFollow a log live#
tail -f keeps running and prints new lines as they are added. It is one of the most useful commands on a server:
tail -f app.logPress Ctrl+C to stop. Here we run it for one second, while another command adds a line:
(sleep 0.3; echo "2026-11-05 09:08 INFO New line" >> app.log) &
timeout 1 tail -f -n 1 app.log2026-11-05 09:07 INFO User asha logged out
2026-11-05 09:08 INFO New lineCount with wc#
wc counts lines, words and bytes:
wc app.log
wc -l app.log 9 53 353 app.log
9 app.logCompare files#
diff shows the differences between two files:
echo -e "apple\nbanana\ncherry" > a.txt
echo -e "apple\nblueberry\ncherry" > b.txt
diff a.txt b.txt2c2
< banana
---
> blueberry2c2 means that line 2 changed. < is from the first file, and > from the second. diff -u gives the format used by Git.
What kind of file is it?#
File names do not need extensions. file looks at the content:
file app.log /bin/ls /etcapp.log: ASCII text
/bin/ls: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=44900829b39271d878615772bb2a6ffa422f0891, for GNU/Linux 3.2.0, stripped
/etc: directoryCommon mistakes#
Practice#
Practice exercise
Print lines 3 and 4 of app.log by combining head and tail.
Show hint
Take the first 4 lines, then the last 2 of those.
Show solution
head -n 4 app.log | tail -n 22026-11-05 09:02 WARN Disk 80 percent full
2026-11-05 09:03 INFO User ravi logged inKey takeaway#
Next: Pipes and Redirection.
Finished this lesson?