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.
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?
file, ls -lh, wc -lcatlesshead / tailtail -fzcat, zless, zgrepBefore 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:
file app.json passwd.gz run.sh windows.txt /usr/bin/ls /var/logapp.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| Result | Meaning | Read it with |
|---|---|---|
JSON text data, ASCII text, shell script | text | cat, less |
gzip compressed data | compressed | zcat, zless |
ELF ... executable | a compiled program | don't cat it: you'll get garbage |
with CRLF line terminators | text saved on Windows (more on this below) | |
directory | a folder | ls |
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?
ls -lh /var/log/syslog # size in KB / MB / GB
wc -l /var/log/syslog # number of linesA 20-line config file? cat it. A 2-million-line log? less, tail or grep, never cat.
stat: everything about one file
stat /etc/hostsWhat it does: shows all the metadata the filesystem keeps about a file.
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| Field | Meaning |
|---|---|
Size | size in bytes |
regular file | the type |
Inode | the file's internal ID number (covered in the links lesson) |
Access: (0644/-rw-r--r--) | permissions, as a number and as letters |
Uid / Gid | owner and group |
Access (time) | last time it was read |
Modify | last time its contents changed. This is the date ls -l shows. |
Change | last time its metadata changed (permissions, owner, name) |
Birth | when 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.
| Command | What it does |
|---|---|
cat file | print the file |
cat -n file | print it with line numbers |
cat a b c | print several files one after another. That's the original meaning of concatenate. |
cat -A file | show invisible characters: tabs, line endings |
tac file | print it backwards, last line first (cat spelled backwards) |
nl file | number the lines (like cat -n) |
cat abc.txt tabs.txt
tac abc.txtfirst
second
third
name port
web 8080third
second
firstcat 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:
cat -A tabs.txt
cat -A windows.txtname^Iport$
web^I8080$line one^M$
line two^M$| Symbol | Means |
|---|---|
$ | the end of a line (the normal Linux "newline") |
^I | a tab character |
^M | a 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:
sed -i 's/\r$//' script.sh # or: dos2unix script.shYAML files (Kubernetes, Ansible, CI pipelines) are fussy about tabs versus spaces, which cat -A also shows.
Small files with cat and wc
Count how many lines the order log has.
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
cat /etc/shopapp/shopapp.conf| Part | Meaning |
|---|---|
cat | short for concatenate (join files together). With one file, it simply prints it. |
/etc/shopapp/shopapp.conf | the file to print |
# Shop application settings
port=8080
environment=production
workers=4
payment_provider=sandboxThe 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
cat -n /etc/shopapp/shopapp.confWhat -n does: numbers every line. Handy when an error message says "syntax error on line 4".
1 # Shop application settings
2 port=8080
3 environment=production
4 workers=4
5 payment_provider=sandbox3. Count before you open: wc
wc /etc/shopapp/shopapp.confWhat it does: wc (word count) counts the lines, words and bytes in a file.
5 8 96 /etc/shopapp/shopapp.conf| Number | Meaning |
|---|---|
5 | lines |
8 | words (anything separated by spaces) |
96 | bytes (characters, roughly) |
Most of the time you only want the number of lines:
wc -l /var/log/shopapp/orders.logWhat -l does: counts lines only. Since logs usually have one event per line, wc -l tells you "how many events".
5000 /var/log/shopapp/orders.log5,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?
file /etc/shopapp/shopapp.conf /root/mystery-fileWhat 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.
/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
catit, you'll get pages of garbage characters, and sometimes a scrambled terminal. If that happens, typeresetand press Enter.
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:
wc -l < /var/log/shopapp/orders.log > /root/line-count.txtWhat each part does
wc -l: count lines.< FILEfeeds the file as input, so wc prints only the number (withwc -l FILEit would also print the file name).>saves the number.
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.
less /var/log/syslogOnce inside, the prompt disappears and you use keys:
| Key | Action |
|---|---|
↓ ↑, or j k | one line down / up |
Space or PgDn / b or PgUp | one screen down / back |
G / g | jump to the end / the beginning |
50g | jump to line 50 |
/word + Enter | search forward. Matches are highlighted. |
?word + Enter | search backward. Great after G, to find the latest occurrence. |
n / N | next / previous match |
&word | show only lines containing "word" (& + Enter to show all again) |
F | follow the file like tail -f. Ctrl + C stops following. |
-N + Enter | toggle line numbers |
h | help, the full list of keys |
q | quit |
Options when opening it:
| Command | Effect |
|---|---|
less -N file | show line numbers |
less +G file | open at the end, the usual way to open a log |
less -S file | don't wrap long lines (scroll sideways with →), good for wide logs |
less -i file | searches 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.)
Big files with less
Search the order log page by page and find the failed order.
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
less /var/log/shopapp/orders.logWhat 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.
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.logEach 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):
| Key | Action |
|---|---|
↓ / ↑ or j / k | one line down / up |
Space or Page Down | one screen down |
b or Page Up | one screen back |
G | jump to the end of the file (the newest lines in a log) |
g | jump to the beginning |
q | quit |
Try G to jump to the end, then g to go back to the start.
3. Search
| Key | Action |
|---|---|
/word then Enter | search forward for "word" (matches get highlighted) |
n | next match |
N | previous match |
?word then Enter | search 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.
2026-11-24 14:17:12 order_id=ORD-103172 amount=1549 status=FAILED reason=card_declinedThe 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
| Command | What it does |
|---|---|
less -N file | show line numbers in the left margin |
less +G file | open 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.
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:
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/FAILEDto search,nfor the next match) orgrep. - Write the real order ID you found.
ORD-000000is only a placeholder.
head and tail: just one end
| Command | Shows |
|---|---|
head file | the first 10 lines |
head -n 3 file | the first 3 lines |
head -c 20 file | the first 20 bytes |
tail file | the last 10 lines |
tail -n 50 file | the last 50 lines |
tail -n +2 file | everything from line 2 on, which skips a header line in CSV files |
head -n -1 file | everything 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:
head -n 110 big.log | tail -n 11head 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.)
Just the start or the end
Save the 20 most recent orders to a file.
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
head -n 3 /var/log/shopapp/orders.log| Part | Meaning |
|---|---|
head | print the beginning of a file |
-n 3 | how many lines: 3 (without it, 10) |
/var/log/shopapp/orders.log | the file |
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=OKThe first three orders of the day, starting at 09:00.
2. The last lines
tail -n 3 /var/log/shopapp/orders.logWhat it does: prints the last 3 lines of the file.
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=OKThe 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
| Command | What it prints |
|---|---|
head -n -2 file | everything except the last 2 lines |
tail -n +2 file | everything 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:
head -n 3174 /var/log/shopapp/orders.log | tail -n 5What 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.
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=OKThe orders right before and after went through fine, so the problem was this customer's card, not the shop.
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
tail -n 20 /var/log/shopapp/orders.log > /root/last-orders.txtWhat each part does
tail -n 20 FILE: print the last 20 lines (newest entries are at the bottom of a log).>saves them.
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:
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:
Filter while you follow. On a busy server, combine it with
grepto see only what matters:tail -f /var/log/nginx/access.log | grep " 500 "Use
-Ffor long watches. Logs are rotated: renamed toaccess.log.1and replaced by a new, emptyaccess.log, usually once a night.tail -fkeeps reading the old renamed file and goes quiet.tail -Fnotices the switch and follows the new file.
Log rotation, and why tail -F matters
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.
Watch a live log
Follow the live log and catch the incident code in the alert.
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
tail -n 5 /var/log/shopapp/live.log2026-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 62msA 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
tail -f /var/log/shopapp/live.log| Part | Meaning |
|---|---|
tail | print the end of the file |
-f | follow: don't exit, keep printing new lines as they arrive |
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:
tail -f /var/log/shopapp/live.log | grep ALERTWhat 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.
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
tail -f /var/log/shopapp/live.log | grep ALERTPress Ctrl + C once you see an alert, then:
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 ALERTshows only the alert lines.- Press Ctrl+C to stop watching once the alert appears. Write the incident ID you saw (
INC-0000is a placeholder).
wc: count lines, words and bytes
wc abc.txt tabs.txt /etc/passwd 3 3 19 abc.txt
2 4 19 tabs.txt
20 24 958 /etc/passwd
25 31 996 totalThree numbers per file: lines, words, bytes, then a total when you give several files.
| Command | Counts |
|---|---|
wc -l file | lines, by far the most used: "how many requests / errors / users?" |
wc -w file | words |
wc -c file | bytes |
wc -l < file | lines, 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:
| Command | Like | Does |
|---|---|---|
zcat file.gz | cat | print the uncompressed contents |
zless file.gz | less | page through it |
zgrep ERROR file.gz | grep | search inside it |
zcat passwd.gz | head -2root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinThe 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:
Nov 24 15:02:30 web-01 nginx[1234]: upstream timed out while connecting to 10.0.3.7:8080| Part | Meaning |
|---|---|
Nov 24 15:02:30 | when it happened (check the server's time zone) |
web-01 | where: 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 -lhandwc -l(how big?),stat(all its metadata). catfor short files;cat -Areveals tabs (^I) and Windows line endings (^M);tacreverses.lessfor anything long:Space/b,G/g,/word+n,Fto follow,qto quit. Open logs withless +G.head -n Nandtail -n Nfor the start or end;tail -n +2skips a header.tail -ffollows a live log,tail -Fsurvives rotation; filter with| grep.wc -lcounts lines.zcat,zless,zgrepread compressed logs directly.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.