Basic

Reading files from the terminal

Most of the time with a file is spent reading it, and reading it well is a skill. cat for small files, head and tail for big ones, less for scrolling, and grep for finding. Choosing the wrong one fills your terminal with ten thousand lines.

What you will see

1 2 3 then 19998 19999 20000. Six lines total, and you know the shape of the whole file.

About 2 min of reading

Try It

Sample a large file without dumping it.

1

Make a big file

seq 1 20000 > big.txt && wc -l big.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
20000 - the count you would have read before printing.
2

Sample both ends

head -3 big.txt; tail -3 big.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
1 2 3 then 19998 19999 20000. Six lines total, and you know the shape of the whole file.

Data Flow

A file is sampled rather than dumped.
1 Check the size with wc
↓
2 Sample the start with head
↓
3 Search with grep for a specific thing
↓
4 Open less only for real reading
Why this works
Count before you print

wc -l file tells you the size before you cat it. A 400,000 line file printed to the terminal is unreadable and slow, and the count would have told you in one command.

Binary files are not text

cat on a binary prints garbage and can leave odd characters in your terminal. grep -l or file tells you the type first, and the habit of checking type is what keeps a session usable.

Examples

head and tail bound the cost

head -20 shows the start of a file and tail -20 shows the end, which is where logs put the newest line. Neither loads the whole file into your view, so they are the default for anything you have not already sized.

less for scrolling

less opens the file in a pager you can page through and search. It is the right tool when you want to read rather than sample, and it leaves the terminal in a state you have to quit from, which is worth knowing.

grep finds, it does not read

grep pattern file gives the matching lines with their numbers when you ask for -n. That is a different question from 'what is in this file', and asking the wrong one gives a confident but useless answer.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Creating and moving files
Previous Lesson
Creating and moving files
Next Lesson
Redirects and pipes
Redirects and pipes →