Module 1: Terminal BasicsLesson 6 of 7
0%
Lesson 6ยท4 min

Reading and Editing Files

View and modify file contents from the terminal

Reading and Editing Files

Let's learn how to peek inside files and make changes.

Reading Files: cat

cat displays the entire file contents:

Terminal
$ cat package.json
{
"name": "my-app",
"version": "1.0.0"
}
โ–Œ

Tip

For long files, cat dumps everything at once. Use less instead to scroll through pages.

Reading Long Files: less

Terminal
$ less long-file.txt
# Use arrow keys to scroll
# Press 'q' to quit
# Press '/' to search
โ–Œ

Reading Just Parts

Terminal
# First 10 lines
$ head file.txt
# Last 10 lines
$ tail file.txt
# First 20 lines
$ head -n 20 file.txt
# Watch a log file update in real-time
$ tail -f app.log
โ–Œ

Quick Edits: echo and Redirection

Terminal
# Write text to a file (overwrites!)
$ echo "Hello World" > greeting.txt
# Append text to a file (adds to end)
$ echo "More text" >> greeting.txt
$ cat greeting.txt
Hello World
More text
โ–Œ

Warning

> overwrites the entire file! Use >> to append without losing existing content.

Terminal Text Editors

nano (Easiest)

Terminal
$ nano file.txt
โ–Œ
  • Edit with arrow keys
  • Save: Ctrl + O, then Enter
  • Exit: Ctrl + X

Aussie Note

nano is like texting - simple and gets the job done. Perfect for quick edits! ๐Ÿ“ฑ

vim (Powerful but Tricky)

Terminal
$ vim file.txt
โ–Œ

Warning

First time in vim? If you're stuck: 1. Press Esc (maybe a few times) 2. Type :q! and press Enter to quit without saving 3. Or :wq to save and quit

vim is powerful but has a learning curve. nano is fine for now!

VS Code from Terminal

If you have VS Code installed:

Terminal
$ code file.txt # Open file in VS Code
$ code . # Open current folder in VS Code
$ code ~/projects/my-app # Open a project
โ–Œ

Tip

For most editing, code . to open VS Code is the easiest option. Terminal editing is great for quick changes on servers.

Searching in Files: grep

Terminal
# Find lines containing "error"
$ grep "error" app.log
# Search all files in a folder
$ grep -r "TODO" src/
# Show line numbers
$ grep -n "function" script.js
โ–Œ

Quick Reference

CommandWhat it does
cat fileShow entire file
less fileScroll through file
head fileShow first 10 lines
tail fileShow last 10 lines
nano fileEdit in nano
code fileOpen in VS Code
echo "text" > fileWrite to file
echo "text" >> fileAppend to file
grep "text" fileSearch in file