HEAD - View beginning of file
head file.txt
head -n 20 file.txt
head -20 file.txt
head -c 100 file.txt
head file1.txt file2.txt
TAIL - View end of file
tail file.txt
tail -n 20 file.txt
tail -20 file.txt
tail -c 100 file.txt
tail file1.txt file2.txt
Follow file (tail -f)
tail -f /var/log/syslog
tail -F /var/log/app.log
tail -n 50 -f /var/log/nginx/access.log
tail -f /var/log/nginx/*.log
Skip lines (tail)
tail -n +10 file.txt
tail -n +100 file.txt
Skip lines (head)
head -n -5 file.txt
Combine head and tail
head -n 20 file.txt | tail -n 10
tail -n +100 file.txt | head -n 10
sed -n '100,110p' file.txt
With line numbers
head -n 20 file.txt | nl
tail -n 20 file.txt | cat -n
head -n 20 file.txt | awk '{print NR": "$0}'
Common use cases
View log files
tail -100 /var/log/syslog
tail -f /var/log/apache2/error.log
tail -1000 /var/log/app.log
Check file headers
head -1 data.csv
head -5 data.csv
Monitor multiple logs
tail -f /var/log/nginx/*.log
tail -f /var/log/nginx/{access,error}.log
Extract data range
head -60 file.txt | tail -11
tail -n +2 data.csv
Advanced tail options
tail -q -f *.log
tail -v file.txt
tail -f -s 5 file.txt
tail -f --pid=1234 file.txt
Real-time monitoring
tail -f /var/log/apache2/access.log | grep "404"
tail -f /var/log/syslog | grep --color=auto "error"
tail -f app.log | grep -E "ERROR|WARN"
Performance
time tail -100 huge.log
time head -100 huge.log
Alternatives
less +G file.txt
more file.txt
sed -n '1,10p' file.txt
sed -n '$p' file.txt
awk 'NR<=10' file.txt
Practical examples
Check recent errors
tail -100 /var/log/syslog | grep -i error
Monitor deployment
tail -f /var/log/deploy.log
Extract CSV data
tail -n +2 data.csv > data-only.csv
head -1 data.csv > header.csv
Split file
head -n $(( $(wc -l < file.txt) / 2 )) file.txt > first-half.txt
tail -n $(( $(wc -l < file.txt) / 2 )) file.txt > second-half.txt
Follow with context
tail -f /var/log/app.log | while read line; do
echo "$(date '+%H:%M:%S') $line"
done
Tips
tail -f /var/log/syslog
tail -F /var/log/app.log
tail -f access.log | grep "POST"
tail -100 error.log > recent-errors.txt
head -5 file.txt && echo "..." && tail -5 file.txt
Quick reference
head file.txt
head -n 20 file.txt
head -c 100 file.txt
tail file.txt
tail -n 20 file.txt
tail -f file.txt
tail -F file.txt
head -20 file.txt | tail -10
tail -n +10 file.txt
head -n -5 file.txt