Bash Tutorial · Bash Basics · Lesson 6 of 30
Bash Viewing Files
Read files with cat, head, tail and less, and count lines, words and bytes with wc.
Printing files
cat fileprints a whole file.head -n 5 fileprints the first 5 lines;tail -n 5the last 5.tail -f app.logfollows a growing log file (Ctrl+C to stop).less fileopens a scrollable viewer (qquits,/textsearches).
seq 1 10 > numbers.txt
head -n 3 numbers.txt
echo ---
tail -n 2 numbers.txt
echo ---
sed -n '4,6p' numbers.txt
Output
1 2 3 --- 9 10 --- 4 5 6
Run this on your computer — see “Get Started” for setup.
Counting
wc -l counts lines, wc -w words, wc -c bytes.
printf 'error: disk full\ninfo: started\nerror: timeout\n' > app.log
wc -l app.log
wc -w < app.log
grep -c error app.log
Output
3 app.log 7 2
Run this on your computer — see “Get Started” for setup.
Test yourself
Which command shows the last 20 lines of a log and keeps printing new lines?
head -n 20 app.logcat -f app.logtail -n 20 -f app.logless +20 app.log
Show answer
Answer: tail -n 20 -f app.log