Reading and Editing Files
Let's learn how to peek inside files and make changes.
Reading Files: cat
cat displays the entire file contents:
$ 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
$ less long-file.txt
# Use arrow keys to scroll
# Press 'q' to quit
# Press '/' to search
โ
Reading Just Parts
# 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
# 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)
- 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)
โ 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:
$ 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
# 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
| Command | What it does |
|---|
cat file | Show entire file |
less file | Scroll through file |
head file | Show first 10 lines |
tail file | Show last 10 lines |
nano file | Edit in nano |
code file | Open in VS Code |
echo "text" > file | Write to file |
echo "text" >> file | Append to file |
grep "text" file | Search in file |