TutsFx logo

Linux Command Line Basics

Reading and Searching Files

2 min read Last updated 45 minutes ago

Reading files is a constant task. Here are the commands you will reach for every day.

Quick look with cat

cat prints a file's entire contents:

bash
cat /etc/hostname

Large files with less

For anything longer than a screen, use less. It lets you scroll and search:

bash
less /var/log/syslog
Key Action
Space / PgDn Scroll down
b / PgUp Scroll up
/ Search forward, then n for next match
q Quit

`cat` vs `less`

Use cat for short files and less for anything long. less is safe even on enormous files because it only reads what you view.

Just the top or bottom with head and tail

bash
head -20 access.log      # first 20 lines
tail -20 access.log      # last 20 lines
tail -f access.log       # follow new lines as they are written

tail -f is invaluable for watching live logs. Press Ctrl + C to stop.

i

Never `cat` a log

Logs can be thousands of lines. cat /var/log/syslog floods your screen — use less or tail instead.

Searching with grep

grep searches files for a pattern:

bash
grep "error" /var/log/syslog       # every line containing "error"
grep -i "error" log.txt            # ignore case
grep -n "error" log.txt            # show line numbers
grep -r "TODO" ~/projects          # search an entire directory

Piping: the glue of the shell

The pipe symbol | takes the output of one command and feeds it into another:

bash
ls -la | grep "jan"       # only files modified in January
grep "error" log.txt | head -20   # first 20 matching lines

Try it

  1. grep -i "root" /etc/passwd — find lines mentioning root
  2. ls -la / | head — first ten entries of the root directory
  3. tail -n 5 /etc/passwd — the last five lines
Share:

We value your privacy

We use cookies to enhance your browsing experience, serve personalized ads, and analyze traffic. By clicking "Accept", you consent to our use of cookies. Read our Privacy Policy to learn more.