Learn / Linux / Getting Started
Lesson 6 of 74

Reading Files

Choose the right tool for every file. Check what a file is with file and stat, print short files with cat, page and search huge logs with less, take the start or end with head and tail, follow live logs with tail -f, count with wc and read compressed logs without unpacking them.

25 min read Report a problem Hands-on lab included 6-question quiz

Text files everywhere

On a Linux server, almost everything you need to read is a plain text file: configuration in /etc, logs in /var/log, scripts, service definitions, even system information in /proc. Being fast at reading files is being fast at operating servers.

The skill is choosing the right tool for the size of the file and what you're looking for:

Which command should I use?

Not sure what it is?file, ls -lh, wc -l
Short filefits on screen: cat
Long fileread or search: less
Just the start / endhead / tail
Growing right nowtail -f
Compressed (.gz)zcat, zless, zgrep

Before you open it: what is it?

file: what kind of file?

Linux doesn't rely on extensions like .txt. A file called backup could be text, a compressed archive or a program. file looks at the actual contents and tells you:

bash
file app.json passwd.gz run.sh windows.txt /usr/bin/ls /var/log
text
app.json:    JSON text data
passwd.gz:   gzip compressed data, was "passwd", last modified: Tue Nov 24 03:44:16 2026, from Unix, original size modulo 2^32 958
run.sh:      Bourne-Again shell script, ASCII text executable
windows.txt: ASCII text, with CRLF line terminators
/usr/bin/ls: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, ...
/var/log:    directory
ResultMeaningRead it with
JSON text data, ASCII text, shell scripttextcat, less
gzip compressed datacompressedzcat, zless
ELF ... executablea compiled programdon't cat it: you'll get garbage
with CRLF line terminatorstext saved on Windows (more on this below)
directorya folderls

If you ever cat a binary file by mistake and your terminal starts showing strange symbols, type reset and press Enter.

How big is it?

text
ls -lh /var/log/syslog        # size in KB / MB / GB
wc -l /var/log/syslog         # number of lines

A 20-line config file? cat it. A 2-million-line log? less, tail or grep, never cat.

stat: everything about one file

bash
stat /etc/hosts

What it does: shows all the metadata the filesystem keeps about a file.

text
  File: /etc/hosts
  Size: 20        	Blocks: 8          IO Block: 4096   regular file
Device: 254,0	Inode: 1474674     Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2026-11-24 15:18:54.742112553 +0530
Modify: 2026-11-24 15:18:54.822112558 +0530
Change: 2026-11-24 15:18:55.866112620 +0530
 Birth: 2026-11-24 15:18:54.742112553 +0530
FieldMeaning
Sizesize in bytes
regular filethe type
Inodethe file's internal ID number (covered in the links lesson)
Access: (0644/-rw-r--r--)permissions, as a number and as letters
Uid / Gidowner and group
Access (time)last time it was read
Modifylast time its contents changed. This is the date ls -l shows.
Changelast time its metadata changed (permissions, owner, name)
Birthwhen it was created (not every filesystem records this)

cat: print the whole file

cat prints files to the screen in one go. Perfect for short files like most configs.

CommandWhat it does
cat fileprint the file
cat -n fileprint it with line numbers
cat a b cprint several files one after another. That's the original meaning of concatenate.
cat -A fileshow invisible characters: tabs, line endings
tac fileprint it backwards, last line first (cat spelled backwards)
nl filenumber the lines (like cat -n)
bash
cat abc.txt tabs.txt
tac abc.txt
text
first
second
third
name	port
web	8080
text
third
second
first

cat joined the two files. tac printed abc.txt upside down, which can be handy for logs, where the newest lines are at the bottom.

Seeing the invisible: cat -A

Some problems are caused by characters you can't see. cat -A reveals them:

bash
cat -A tabs.txt
cat -A windows.txt
text
name^Iport$
web^I8080$
text
line one^M$
line two^M$
SymbolMeans
$the end of a line (the normal Linux "newline")
^Ia tab character
^Ma carriage return: part of Windows line endings

Linux ends each line with one character (LF, \n). Windows uses two (CR LF, \r\n). A shell script edited on Windows and copied to a server often fails with confusing errors like /bin/bash^M: bad interpreter or $'\r': command not found. file warns you (with CRLF line terminators), and the fix is one command:

text
sed -i 's/\r$//' script.sh        # or: dos2unix script.sh

YAML files (Kubernetes, Ansible, CI pipelines) are fussy about tabs versus spaces, which cat -A also shows.

Try it · Task 1 of 4

Small files with cat and wc

Count how many lines the order log has.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

cat prints a whole file to the screen in one go. It's perfect for files that fit on the screen, like most config files. For a 5,000-line log it's the wrong tool: everything scrolls past in a blink and you only see the end. So before opening an unknown file, it's worth checking how big it is and what kind of file it is.

1. Print a small file

bash
cat /etc/shopapp/shopapp.conf
PartMeaning
catshort for concatenate (join files together). With one file, it simply prints it.
/etc/shopapp/shopapp.confthe file to print
text
# Shop application settings
port=8080
environment=production
workers=4
payment_provider=sandbox

The file's exact contents. The first line starts with #: in most config files that marks a comment, a note for humans that the program ignores.

2. Add line numbers

bash
cat -n /etc/shopapp/shopapp.conf

What -n does: numbers every line. Handy when an error message says "syntax error on line 4".

text
     1	# Shop application settings
     2	port=8080
     3	environment=production
     4	workers=4
     5	payment_provider=sandbox

3. Count before you open: wc

bash
wc /etc/shopapp/shopapp.conf

What it does: wc (word count) counts the lines, words and bytes in a file.

text
 5  8 96 /etc/shopapp/shopapp.conf
NumberMeaning
5lines
8words (anything separated by spaces)
96bytes (characters, roughly)

Most of the time you only want the number of lines:

bash
wc -l /var/log/shopapp/orders.log

What -l does: counts lines only. Since logs usually have one event per line, wc -l tells you "how many events".

text
5000 /var/log/shopapp/orders.log

5,000 lines: far too many for cat. And ls -lh /var/log/shopapp tells you it's about 300 KB.

4. What kind of file is it?

bash
file /etc/shopapp/shopapp.conf /root/mystery-file

What it does: looks at a file's contents (not its name) and tells you what kind of file it is. Linux doesn't need extensions like .txt, so this is how you check.

text
/etc/shopapp/shopapp.conf: ASCII text
/root/mystery-file:        ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, ...
  • ASCII text: plain text, safe to read with cat.
  • ELF ... executable: a compiled program, not text. If you cat it, you'll get pages of garbage characters, and sometimes a scrambled terminal. If that happens, type reset and press Enter.
2 · Your task

Find out how many lines /var/log/shopapp/orders.log has and save just the number to /root/line-count.txt.

Expected result: cat /root/line-count.txt prints the number of lines.

Hint: the commands, explained

wc -l FILE prints the number followed by the file name. If you feed the file in with < instead, wc doesn't know the name and prints only the number:

text
wc -l < /var/log/shopapp/orders.log > /root/line-count.txt

What each part does

  • wc -l: count lines. < FILE feeds the file as input, so wc prints only the number (with wc -l FILE it would also print the file name).
  • > saves the number.
First start the lab machine in the terminal panel on the right.

less: read and search big files

less opens a file in a viewer. It shows one screen at a time, lets you scroll and search, never changes the file, and opens multi-gigabyte files instantly because it only reads the part you look at.

text
less /var/log/syslog

Once inside, the prompt disappears and you use keys:

KeyAction
↓ ↑, or j kone line down / up
Space or PgDn / b or PgUpone screen down / back
G / gjump to the end / the beginning
50gjump to line 50
/word + Entersearch forward. Matches are highlighted.
?word + Entersearch backward. Great after G, to find the latest occurrence.
n / Nnext / previous match
&wordshow only lines containing "word" (& + Enter to show all again)
Ffollow the file like tail -f. Ctrl + C stops following.
-N + Entertoggle line numbers
hhelp, the full list of keys
qquit

Options when opening it:

CommandEffect
less -N fileshow line numbers
less +G fileopen at the end, the usual way to open a log
less -S filedon't wrap long lines (scroll sideways with →), good for wide logs
less -i filesearches ignore upper/lower case

man pages open in less, and git log and systemctl status use a pager that works the same way. Learn these keys once and you can use them everywhere. (more is an older, simpler pager; less does everything more does and more, hence the name.)

Try it · Task 2 of 4

Big files with less

Search the order log page by page and find the failed order.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

less opens a file in a viewer: one screen at a time, with scrolling and searching, and it never changes the file. It also opens huge files instantly, because it only reads the part you're looking at. Whenever a file is longer than your screen, reach for less.

You already used a viewer like this: man pages open in less.

1. Open the file

bash
less /var/log/shopapp/orders.log

What it does: shows the first screenful of the order log. The prompt disappears because you're inside less now. The last line shows the file name, or a : waiting for a key.

text
2026-11-24 09:00:06 order_id=ORD-100001 amount=2023 status=OK
2026-11-24 09:00:12 order_id=ORD-100002 amount=608 status=OK
2026-11-24 09:00:18 order_id=ORD-100003 amount=4705 status=OK
...
/var/log/shopapp/orders.log

Each line is one order: the date and time, an order ID, the amount and the status. Lines are in time order, oldest first.

2. Move around

These keys work inside less (and inside man):

KeyAction
↓ / ↑ or j / kone line down / up
Space or Page Downone screen down
b or Page Upone screen back
Gjump to the end of the file (the newest lines in a log)
gjump to the beginning
qquit

Try G to jump to the end, then g to go back to the start.

3. Search

KeyAction
/word then Entersearch forward for "word" (matches get highlighted)
nnext match
Nprevious match
?word then Entersearch backward, handy after G to find the latest occurrence

All the good orders say status=OK. Type /FAILED and press Enter: less jumps to the first line containing FAILED and highlights it. If it says Pattern not found, check the spelling: searches are case-sensitive.

text
2026-11-24 14:17:12 order_id=ORD-103172 amount=1549 status=FAILED reason=card_declined

The failed order, its time, its amount and the reason: card_declined, the customer's bank refused the payment. That's the answer support needs.

4. Two useful options

CommandWhat it does
less -N fileshow line numbers in the left margin
less +G fileopen the file already at the end, the usual way to open a log

Avoid opening large logs with an editor like nano or vim on a server: editors load the whole file into memory and can modify it by accident. less is read-only and fast, even on multi-gigabyte files.

2 · Your task

Find the failed order in /var/log/shopapp/orders.log and save its order ID (for example ORD-123456) to /root/failed-order.txt.

Expected result: cat /root/failed-order.txt prints the ID of the order with status=FAILED.

Hint: the commands, explained

Open the file with less, type /FAILED, press Enter, note the order_id, press q, then:

text
echo ORD-000000 > /root/failed-order.txt

(with the real ID instead of the zeros).

What each part does

  • You found the failed order by reading the log with less (type /FAILED to search, n for the next match) or grep.
  • Write the real order ID you found. ORD-000000 is only a placeholder.
First start the lab machine in the terminal panel on the right.

head and tail: just one end

CommandShows
head filethe first 10 lines
head -n 3 filethe first 3 lines
head -c 20 filethe first 20 bytes
tail filethe last 10 lines
tail -n 50 filethe last 50 lines
tail -n +2 fileeverything from line 2 on, which skips a header line in CSV files
head -n -1 fileeverything except the last line

Logs grow at the bottom, so tail is what you want for "what just happened?". head is useful for the column names of a CSV file, the first lines of a config file, or the oldest entries in a log.

They combine to cut a slice out of the middle. Lines 100 to 110:

text
head -n 110 big.log | tail -n 11

head keeps the first 110 lines, and the pipe | hands them to tail, which keeps the last 11 of those. (sed -n '100,110p' big.log does the same; you'll meet sed later.)

Try it · Task 3 of 4

Just the start or the end

Save the 20 most recent orders to a file.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Often you don't need the whole file, just one end of it:

  • The start (head): column headers of a CSV file, the first lines of a config, the oldest entries of a log.
  • The end (tail): the newest entries of a log. This is the one you'll use most: "what happened just now?" is always at the bottom.

Both show 10 lines by default, and -n NUMBER changes that.

1. The first lines

bash
head -n 3 /var/log/shopapp/orders.log
PartMeaning
headprint the beginning of a file
-n 3how many lines: 3 (without it, 10)
/var/log/shopapp/orders.logthe file
text
2026-11-24 09:00:06 order_id=ORD-100001 amount=2023 status=OK
2026-11-24 09:00:12 order_id=ORD-100002 amount=608 status=OK
2026-11-24 09:00:18 order_id=ORD-100003 amount=4705 status=OK

The first three orders of the day, starting at 09:00.

2. The last lines

bash
tail -n 3 /var/log/shopapp/orders.log

What it does: prints the last 3 lines of the file.

text
2026-11-24 17:19:48 order_id=ORD-104998 amount=8431 status=OK
2026-11-24 17:19:54 order_id=ORD-104999 amount=5888 status=OK
2026-11-24 17:20:00 order_id=ORD-105000 amount=6649 status=OK

The latest three orders, ending at 17:20. Together with head, you now know the log covers 09:00 to 17:20 without reading the 4,994 lines in between.

3. Two handy variations

CommandWhat it prints
head -n -2 fileeverything except the last 2 lines
tail -n +2 fileeverything from line 2 onwards, so it skips a header line

tail -n +2 is a classic for CSV files, where the first line holds the column names.

4. Combine them: a slice from the middle

Lines 3170 to 3174, the orders around the failed one:

bash
head -n 3174 /var/log/shopapp/orders.log | tail -n 5

What it does: head takes the first 3174 lines, and the pipe | hands them to tail, which keeps the last 5 of those. You'll learn pipes properly in the text processing track.

text
2026-11-24 14:17:00 order_id=ORD-103170 amount=7138 status=OK
2026-11-24 14:17:06 order_id=ORD-103171 amount=6789 status=OK
2026-11-24 14:17:12 order_id=ORD-103172 amount=1549 status=FAILED reason=card_declined
2026-11-24 14:17:18 order_id=ORD-103173 amount=8990 status=OK
2026-11-24 14:17:24 order_id=ORD-103174 amount=9007 status=OK

The orders right before and after went through fine, so the problem was this customer's card, not the shop.

2 · Your task

Save the 20 most recent orders (the last 20 lines of /var/log/shopapp/orders.log) to /root/last-orders.txt.

Expected result: /root/last-orders.txt has 20 lines, ending with order ORD-105000.

Hint: the commands, explained
text
tail -n 20 /var/log/shopapp/orders.log > /root/last-orders.txt

What each part does

  • tail -n 20 FILE: print the last 20 lines (newest entries are at the bottom of a log). > saves them.
First start the lab machine in the terminal panel on the right.

tail -f: watch a log live

During a deployment, an incident or while reproducing a bug, you want to see log lines as they are written:

text
tail -f /var/log/nginx/access.log

-f (follow) prints the last 10 lines, then keeps waiting and prints each new line the moment it arrives. Your prompt doesn't come back until you press Ctrl + C.

Two things worth knowing:

  1. Filter while you follow. On a busy server, combine it with grep to see only what matters:

    text
    tail -f /var/log/nginx/access.log | grep " 500 "
  2. Use -F for long watches. Logs are rotated: renamed to access.log.1 and replaced by a new, empty access.log, usually once a night. tail -f keeps reading the old renamed file and goes quiet. tail -F notices the switch and follows the new file.

Log rotation, and why tail -F matters

access.logbeing written to
midnight
access.log.1yesterday's log (renamed)
access.lognew, empty file: new lines go here

tail -f keeps watching access.log.1. tail -F switches to the new access.log.

You can also follow several files at once: tail -f app.log error.log labels each block with its file name.

Try it · Task 4 of 4

Watch a live log

Follow the live log and catch the incident code in the alert.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

During an incident or a deployment, you want to see log lines as they are written, not run tail again every few seconds. tail -f (follow) prints the last lines, then keeps waiting and prints every new line the moment it's added. It's how engineers watch a deploy go out, or reproduce a bug while a colleague clicks around the website.

1. Look at the live log once

bash
tail -n 5 /var/log/shopapp/live.log
text
2026-11-24 15:02:24 INFO request served in 66ms
2026-11-24 15:02:26 INFO request served in 52ms
2026-11-24 15:02:28 INFO request served in 28ms
2026-11-24 15:02:30 ALERT payment gateway latency high, incident code=INC-4821
2026-11-24 15:02:32 INFO request served in 62ms

A snapshot of the last 5 lines. Run it again in a few seconds and you'll see different lines: the shop writes a new line every 2 seconds. Most are INFO (normal events), but now and then there's an ALERT.

2. Follow it

bash
tail -f /var/log/shopapp/live.log
PartMeaning
tailprint the end of the file
-ffollow: don't exit, keep printing new lines as they arrive
text
2026-11-24 15:05:10 INFO request served in 41ms
2026-11-24 15:05:12 INFO request served in 77ms
2026-11-24 15:05:14 ALERT payment gateway latency high, incident code=INC-4821
2026-11-24 15:05:16 INFO request served in 19ms
...

New lines appear every 2 seconds, live. Your prompt doesn't come back, because tail is still watching. Press Ctrl + C to stop following.

3. Follow and filter

When a log is busy, you can watch only the lines you care about. The pipe | sends tail's output into grep, which keeps only matching lines:

bash
tail -f /var/log/shopapp/live.log | grep ALERT

What it does: follows the log, but shows only lines containing ALERT. Wait about 12 seconds for one to appear, then press Ctrl + C.

Log files get rotated: renamed to app.log.1 and replaced by a new empty app.log, usually at night. Plain tail -f then keeps watching the old renamed file. Use tail -F (capital F) for long-running watches: it notices the rotation and switches to the new file.

2 · Your task

Follow /var/log/shopapp/live.log until an ALERT appears, note the incident code in it, stop following with Ctrl + C, and save the code (for example INC-1234) to /root/incident.txt.

Expected result: cat /root/incident.txt prints the incident code from the alert.

Hint: the commands, explained
text
tail -f /var/log/shopapp/live.log | grep ALERT

Press Ctrl + C once you see an alert, then:

text
echo INC-0000 > /root/incident.txt

(with the real code instead of the zeros).

What each part does

  • tail -f: follow the file, printing new lines as they're written. | grep ALERT shows only the alert lines.
  • Press Ctrl+C to stop watching once the alert appears. Write the incident ID you saw (INC-0000 is a placeholder).
First start the lab machine in the terminal panel on the right.

wc: count lines, words and bytes

bash
wc abc.txt tabs.txt /etc/passwd
text
  3   3  19 abc.txt
  2   4  19 tabs.txt
 20  24 958 /etc/passwd
 25  31 996 total

Three numbers per file: lines, words, bytes, then a total when you give several files.

CommandCounts
wc -l filelines, by far the most used: "how many requests / errors / users?"
wc -w filewords
wc -c filebytes
wc -l < filelines, printing only the number without the file name, handy in scripts

Combined with grep, it answers real questions: grep -c "ERROR" app.log or grep "ERROR" app.log | wc -l tells you how many errors were logged.

Compressed logs

Old logs are usually compressed to save space: syslog.2.gz, access.log.5.gz. You don't need to unpack them to read them:

CommandLikeDoes
zcat file.gzcatprint the uncompressed contents
zless file.gzlesspage through it
zgrep ERROR file.gzgrepsearch inside it
bash
zcat passwd.gz | head -2
text
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin

The original text, read straight from the compressed file.

Reading a log line

Logs look intimidating until you notice that almost every line follows the same structure: when, where, who, what:

text
Nov 24 15:02:30 web-01 nginx[1234]: upstream timed out while connecting to 10.0.3.7:8080
PartMeaning
Nov 24 15:02:30when it happened (check the server's time zone)
web-01where: the host
nginx[1234]who: the program and its process ID
upstream timed out ...what happened

Reading logs is mostly about finding the first line where things went wrong, and the lines just before it.

Opening a large log with cat (it floods the terminal and you only see the end) or with an editor like vim or nano (it loads the whole file into memory and can modify it by accident). On servers: less to read, tail for recent lines, grep to search.

"How do you watch a log file in real time?" tail -f file, or tail -F so it survives log rotation. Pipe it to grep to filter.

"How do you view a 10 GB log file?" With less (it doesn't load the whole file), or tail / grep to pull out only what you need. Never cat or a text editor.

"A script works on your laptop but fails on the server with 'bad interpreter ^M'. Why?" It has Windows (CRLF) line endings. cat -A or file shows it; dos2unix or sed -i 's/\r$//' fixes it.

"How do you count the lines in a file?" wc -l file.

Summary

  • Check first: file (what is it?), ls -lh and wc -l (how big?), stat (all its metadata).
  • cat for short files; cat -A reveals tabs (^I) and Windows line endings (^M); tac reverses.
  • less for anything long: Space/b, G/g, /word + n, F to follow, q to quit. Open logs with less +G.
  • head -n N and tail -n N for the start or end; tail -n +2 skips a header.
  • tail -f follows a live log, tail -F survives rotation; filter with | grep.
  • wc -l counts lines. zcat, zless, zgrep read compressed logs directly.
Check your understanding

Quick quiz

Feedback