iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

cat / less / head / tail

Reading file contents in the shell: cat, less, more, head, tail, and the patterns that beat opening an editor.

Linux — cat / less / head / tail

EXAMPLE
# ===== cat: print files =====
cat file.txt
cat a.txt b.txt > combined.txt    # concatenate
cat -n file.txt                   # number lines
cat -A file.txt                   # show non-printing characters

# Useful pattern:
cat > scratch.txt <<'EOF'
some literal
content
EOF
# Ctrl+D to end if interactive.

# ===== less: paged viewer =====
less file.log
# Inside less:
#   /pattern      search forward
#   ?pattern      search backward
#   n / N         next / previous match
#   g / G         start / end
#   q             quit
#   F             follow (tail -f style; Ctrl+C to stop)
#   -N            toggle line numbers

less -R logfile.log    # interpret ANSI colour escapes
less -S logfile.log    # do NOT wrap long lines (great for wide CSVs)

# Pipe into less to page anything:
git log -p | less -R
ps aux | less

# ===== head: first N lines =====
head file.txt           # default 10 lines
head -n 5 file.txt      # first 5 lines
head -c 200 file.bin    # first 200 BYTES
head -n -2 file.txt     # all but the last 2 lines

# ===== tail: last N lines =====
tail file.txt
tail -n 50 file.txt
tail -n +5 file.txt     # FROM line 5 to end
tail -f /var/log/app.log
tail -F /var/log/app.log    # also handles log rotation
tail -n 100 -f file.log     # last 100 lines + follow

# ===== Combining =====
# Lines 100-150:
sed -n '100,150p' file.txt
# or: head -n 150 file.txt | tail -n 51

# Mid-file with awk:
awk 'NR >= 100 && NR <= 150' file.txt

# ===== Useful pipelines =====
# Top 5 IPs in access log:
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -5

# Tail a JSON log + pretty print with jq:
tail -f app.log | jq .

# Watch a file change without opening an editor:
watch -n 2 'tail -n 20 status.txt'

# ===== Pitfalls =====
# - 'cat foo | grep bar' is a Useless Use of Cat; prefer 'grep bar foo'
# - Editing a file you are 'tail -F'ing in the same terminal can confuse output
# - 'less' that does not show colour: add -R
# - head/tail counts in 'bytes' vs 'lines' if you mix -n and -c

# ===== Patterns to internalise =====
# - less for browsing; cat for piping; head/tail for slicing
# - tail -F (capital F) for log files that rotate
# - less -SR for wide colour-coded CSVs and logs
# - watch + tail for live progress without an editor

Why it matters

cat for short prints, less for browsing, head/tail for slicing, awk/sed for ranges. tail -F handles log rotation; less -SR handles wide colour output. Add watch + tail and you have a live console for any progress file.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
cat file.txt
less huge.log         # q to quit
head -n 20 file
tail -f /var/log/app.log
Try it Yourself »

Discussion

Loading…