Lab 04: Creating and Viewing Files

Objective

Create files in multiple ways, view their contents with different tools, and understand when to use cat, head, tail, less, and wc. These are the bread-and-butter commands for working with log files and config files.

Time: 25 minutes | Level: Foundations | Docker: docker run -it --rm ubuntu:22.04 bash


Step 1: Creating Empty Files with touch

touch /tmp/empty.txt
ls -la /tmp/empty.txt

📸 Verified Output:

-rw-r--r-- 1 root root 0 Mar  5 00:55 /tmp/empty.txt

💡 touch does two things: if the file doesn't exist it creates it (zero bytes). If it does exist, it updates the access/modification timestamps — useful in scripts to signal "this file was processed."


Step 2: Writing Content with echo and Redirection

echo 'Hello, Linux!' > /tmp/hello.txt
cat /tmp/hello.txt

📸 Verified Output:

Hello, Linux!

📸 Verified Output:

💡 > overwrites (destructive). >> appends (safe). This distinction prevents many accidental data losses. When in doubt, use >>.


Step 3: Word Count with wc

📸 Verified Output:

📸 Verified Output:

💡 wc -l is the fastest way to count entries in a log file. wc -l /var/log/auth.log instantly tells you how many authentication events occurred.


Step 4: head and tail for Large Files

📸 Verified Output:

📸 Verified Output:

💡 tail -f /var/log/syslog is one of the most-used monitoring commands — it watches a log file live and prints new lines as they arrive. -f = follow.


Step 5: Line Numbers with cat -n

📸 Verified Output:

📸 Verified Output:

💡 cat -A shows $ at line endings (Unix-style \n). Windows files show ^M$ — the ^M is a carriage return (\r). This causes "^M errors" when running Windows-created scripts on Linux.


Step 6: Viewing Hex/Octal Content

📸 Verified Output:

💡 A=0x41, B=0x42, C=0x43, 0a=\n (newline). Understanding hex is essential for malware analysis, binary file parsing, and network packet inspection.


Step 7: tee — Write and Display Simultaneously

📸 Verified Output:

💡 tee is invaluable in scripts — it lets you pipe output to a file AND to stdout at the same time, so you can both log and display results. command | tee output.log | grep ERROR


Step 8: Capstone — Parse a Simulated Log File

📸 Verified Output:


Summary

Command
Use Case

touch file

Create empty file / update timestamp

echo 'text' > file

Write/overwrite file

echo 'text' >> file

Append to file

cat file

Display entire file

cat -n file

Display with line numbers

head -N file

First N lines

tail -N file

Last N lines

tail -f file

Follow file in real time

wc -l file

Count lines

tee file

Write to file AND stdout

Last updated