Text File Operations and Editors
Now that you're comfortable navigating the file system and managing files, it's time to learn how to work with text files—the lifeblood of Linux system administration and development. In this lesson, you'll master essential text manipulation commands and get hands-on with popular text editors.
Learning Goals:
- Create, view, and manipulate text files using command-line tools
- Master basic text editors: Nano (beginner-friendly) and Vim (power-user)
- Search, filter, and transform text content
- Understand when to use different text editing approaches
Essential Text File Commands
Creating and Viewing Files
Let's start with the basics—creating and examining text files.
# Create an empty file
touch example.txt
# Create a file with initial content using echo
echo "Hello, Linux World!" > greeting.txt
# View entire file content
cat greeting.txt
# View with line numbers
cat -n greeting.txt
# View first few lines
head -5 largefile.txt
# View last few lines
tail -5 logfile.txt
Appending and Combining Files
# Add content to existing file
echo "This is additional text" >> greeting.txt
# Combine multiple files
cat file1.txt file2.txt > combined.txt
# View growing files in real-time (useful for logs)
tail -f /var/log/syslog
Use >> to append content without overwriting existing data. The single > will replace the entire file content!
Text Processing Power Tools
Searching with grep
grep is your go-to tool for searching text patterns.
# Search for a pattern in a file
grep "error" logfile.txt
# Case-insensitive search
grep -i "warning" system.log
# Search recursively in directories
grep -r "TODO" /home/user/projects/
# Show line numbers with matches
grep -n "function" script.py
# Count occurrences
grep -c "success" results.txt
Stream Editing with sed
sed allows you to transform text on the fly.
# Replace first occurrence per line
sed 's/old/new/' file.txt
# Replace all occurrences
sed 's/old/new/g' file.txt
# Delete lines containing pattern
sed '/pattern/d' file.txt
# Edit file in-place (be careful!)
sed -i 's/foo/bar/g' config.txt
Advanced Text Processing with awk
awk is a powerful programming language for text processing.
# Print specific column
ls -l | awk '{print $9}'
# Print lines where condition is true
awk '$3 > 1000 {print $1}' data.txt
# Custom field separator
awk -F: '{print $1}' /etc/passwd
Text Editors: Nano
Nano is a simple, beginner-friendly text editor perfect for quick edits.
Basic Nano Usage
# Open a file
nano document.txt
# Create new file
nano newfile.txt
Nano Keyboard Shortcuts:
Ctrl + O- Save fileCtrl + X- ExitCtrl + K- Cut lineCtrl + U- PasteCtrl + W- SearchCtrl + \- Search and replace
The available shortcuts are always displayed at the bottom of the screen!
Text Editors: Vim
Vim is a powerful modal editor that's worth learning for serious text editing.
Vim Modes and Basics
# Open file in Vim
vim config.txt
Vim has different modes:
- Normal mode: For navigation and commands (default when opening)
- Insert mode: For typing text
- Visual mode: For selecting text
- Command mode: For entering commands
- Basic Commands
- Navigation
# Essential Vim commands (in Normal mode)
i # Enter Insert mode
Esc # Return to Normal mode
:w # Save file
:q # Quit
:wq # Save and quit
:q! # Quit without saving
dd # Delete current line
yy # Copy current line
p # Paste
u # Undo
/text # Search for "text"
# Movement commands
h j k l # Left, Down, Up, Right (or arrow keys)
0 # Beginning of line
$ # End of line
gg # Top of file
G # Bottom of file
Ctrl + f # Page down
Ctrl + b # Page up
Don't panic if you get stuck in Vim! If you can't figure out how to exit, press Esc to ensure you're in Normal mode, then type :q! and press Enter to force quit without saving.
Practical Workflow Examples
Editing Configuration Files
# Backup original config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
# Edit the config
sudo nano /etc/ssh/sshd_config
# Or with Vim
sudo vim /etc/ssh/sshd_config
# View changes
diff /etc/ssh/sshd_config.backup /etc/ssh/sshd_config
Log File Analysis
# Find recent errors in system log
grep -i "error" /var/log/syslog | tail -20
# Count unique IP addresses in web log
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr
# Monitor new log entries in real-time
tail -f /var/log/auth.log | grep "Failed password"
Common Pitfalls
-
Forgetting Vim modes: New users often get stuck because they don't understand Vim's modal nature. Remember to press
Escto return to Normal mode. -
Overwriting files with
>: Usingecho "text" > file.txtwill erase the entire file. Use>>to append instead. -
Editing system files without backup: Always create backups before editing important configuration files.
-
Using wrong line endings: Windows line endings (
\r\n) can cause issues in Linux scripts. Usedos2unixto convert if needed. -
Getting stuck in less/more viewers: When viewing files with
lessormore, pressqto exit.
Summary
You now have a solid foundation in Linux text file operations! You can:
- Create, view, and manipulate text files using command-line tools
- Search and filter content with
grep,sed, andawk - Edit files confidently using both Nano and Vim
- Apply these skills to real-world scenarios like log analysis and configuration editing
Remember: Start with Nano for quick edits, but invest time in learning Vim—it will pay off in the long run for serious text editing tasks.
Quiz
Show quiz
-
Which command would you use to add "new text" to an existing file without removing its current content?
- A)
echo "new text" > file.txt - B)
echo "new text" | file.txt - C)
echo "new text" >> file.txt - D)
cat "new text" file.txt
- A)
-
You need to search for all occurrences of "ERROR" (case-insensitive) in a log file and see the line numbers. Which grep command should you use?
- A)
grep "ERROR" logfile.txt - B)
grep -i "error" logfile.txt - C)
grep -n -i "error" logfile.txt - D)
grep -r "error" logfile.txt
- A)
-
In Vim, which sequence of commands would you use to save a file and exit?
- A)
Ctrl + SthenCtrl + Q - B)
:wqthen Enter - C)
:savethen:quit - D)
Escthen:q
- A)
-
What's the main risk of using
sed -i 's/old/new/g' important_file.txtwithout a backup?- A) It will create multiple copies of the file
- B) It might corrupt binary files
- C) If the command has an error, you could lose your original content
- D) It will change file permissions
-
You're viewing a large file with
lessand want to exit. What do you press?- A)
Esc - B)
Ctrl + C - C)
:q - D)
q
- A)
Answers:
- C - The
>>operator appends to files without overwriting - C -
-nshows line numbers,-imakes search case-insensitive - B -
:wqis the Vim command to write (save) and quit - C -
sed -iedits files in-place, so errors could permanently alter your file - D - Press
qto quit less/more viewers