Skip to content
Linux Administration
Lab 2 of 27·15mBeginner

Read and search files without opening an editor

Use less, head, tail and grep to answer questions about a 200MB log you must never load into memory.

You need

  • A Linux system with a shell

Do first

Opening a log in an editor is a habit worth losing. Editors load the file; these tools stream it.

1. Make something to read

mkdir -p ~/labs/linux-quickstart && cd ~/labs/linux-quickstart
seq 1 100000 | sed 's/^/line /' > big.log
ls -lh big.log

Verify

wc -l big.log # 100000 big.log

2. Look at the ends

head -n 5 big.log
tail -n 5 big.log

For a log, tail is the one you want almost always — the interesting event is the most recent. Watch it live:

tail -f big.log

Nothing happens, because nothing is writing. Leave it running, open a second terminal, and append:

echo "line 100001" >> ~/labs/linux-quickstart/big.log

The line appears in the first terminal. Ctrl-C to stop.

Verify

tail -n 1 big.log # line 100001

3. Page through it

less big.log

Inside less: / searches forward, n repeats the search, G jumps to the end, g to the start, q quits. less does not read the whole file to show you the first screen, which is why it opens instantly on a file that would stall an editor.

4. Search instead of scrolling

grep "line 42" big.log
grep -c "line 4" big.log
grep -n "line 99999" big.log

-c counts instead of printing, -n gives line numbers. The flag you will want most often is -i for case-insensitive, and -r to search a directory tree.

Verify

grep -c "^line 1$" big.log # 1

5. Combine them

grep "line 9999" big.log | wc -l
tail -n 1000 big.log | grep "line 995"

The second form is the important habit: narrow by time with tail first, then filter. On a real log, grepping the whole file when you only care about the last hour is how you wait three minutes for an answer you could have had instantly.

Verify

tail -n 100 big.log | grep -c "line" # 100

Clean up

rm ~/labs/linux-quickstart/big.log

Where this goes next

You can read anything on a box. Next: changing things without breaking them.