dotlinux blog

Editing Text Files Using Nano, Vim, grep & regexps

In the world of system administration, software development, and IT, the ability to efficiently manipulate text files directly on a server or within a terminal is not just a skill—it's a superpower. While modern graphical text editors are excellent for many tasks, they are often unavailable in remote, headless, or minimal environments. This is where command-line text editors and powerful text-processing tools come into their own.

This comprehensive guide will walk you through the essentials of two of the most ubiquitous command-line editors, Nano and Vim, and then elevate your skills by introducing the powerful search tool grep combined with Regular Expressions (regexps). Whether you're quickly editing a configuration file, writing a script, or searching through thousands of log files, mastering these tools will make you significantly more productive.

2026-03

Table of Contents#

  1. The Simple & Intuitive: GNU Nano

  2. The Powerful & Efficient: Vim

  3. Searching Like a Pro: grep

  4. Unlocking Precision: Regular Expressions (regexps)

  5. Putting It All Together: Practical Examples

  6. Conclusion

  7. References & Further Reading


1. The Simple & Intuitive: GNU Nano#

Nano is a straightforward, easy-to-learn text editor perfect for beginners or for quick edits. Its main advantage is that all common commands are displayed at the bottom of the screen.

Opening and Creating Files#

# Open an existing file
nano filename.txt
 
# Create a new file
nano new_filename.conf

Basic Editing and Navigation#

  • Typing: Just start typing. It works like a simple notepad.
  • Arrow Keys: Use the arrow keys to move the cursor around.
  • Ctrl + G: Get help. This shows a full list of commands.

Searching for Text#

  • Ctrl + W: This is the "Where is" command. Press Ctrl+W, type your search term, and press Enter. Press Alt+W to find the next occurrence.

Saving and Exiting#

  • Ctrl + O: "Write Out" (Save). Press Ctrl+O, confirm the filename, and press Enter.
  • Ctrl + X: Exit. If you have unsaved changes, Nano will prompt you to save them.

Why Use Nano?#

  • Low Learning Curve: Ideal for beginners.
  • On-Screen Help: Commands are always visible.
  • Predictable: Behaves like a simple graphical editor.

2. The Powerful & Efficient: Vim#

Vim (Vi IMproved) is a highly powerful and efficient modal editor. It has a steep learning curve but offers unparalleled speed for those who master it. The key to understanding Vim is its modes.

Vim Modes: The Core Concept#

  1. Normal Mode (Default): This is for navigation, deletion, copying, pasting, and other commands. You are not inserting text here. Press Esc to return to Normal Mode from any other mode.
  2. Insert Mode: This is for typing text, like a regular editor. Press i (insert) or a (append) to enter Insert Mode.
  3. Command-Line Mode: For saving, quitting, and searching/replacing. Press : from Normal Mode to enter this mode.

Opening, Saving, and Quitting (Command Mode)#

From Normal Mode, press : to enter Command-Line Mode.

:e filename.txt    " Open (edit) a file
:w                 " Save (write) the file
:q                 " Quit
:wq                " Save and quit
:q!                " Quit without saving (force quit)

Basic Navigation (Normal Mode)#

  • h, j, k, l: Left, Down, Up, Right (instead of arrow keys).
  • w: Move forward to the start of the next word.
  • b: Move backward to the start of the previous word.
  • 0 (zero): Move to the beginning of the line.
  • $: Move to the end of the line.
  • G: Go to the last line of the file.
  • gg: Go to the first line of the file.
  • :25 then Enter: Go to line 25.

Inserting and Editing Text#

From Normal Mode:

  • i: Insert before the cursor.
  • a: Append after the cursor.
  • o: Open a new line below the current line and enter Insert Mode.
  • O: Open a new line above the current line.
  • x: Delete the character under the cursor.
  • dd: Delete (cut) the current line.
  • yy: Yank (copy) the current line.
  • p: Paste the copied or deleted text after the cursor.
  • u: Undo the last action.

Searching and Replacing#

  • Searching:

    • From Normal Mode, press /, type your search term, and press Enter.
    • Press n to go to the next match.
    • Press N to go to the previous match.
  • Replacing (using Command-Line Mode):

    :s/old/new/          " Replace the first occurrence of 'old' with 'new' on the current line.
    :s/old/new/g         " Replace all occurrences of 'old' with 'new' on the current line (g = global).
    :%s/old/new/g        " Replace all occurrences of 'old' with 'new' in the entire file (% = entire file).
    :%s/old/new/gc       " The same, but ask for confirmation (c = confirm) for each replacement.

Why Use Vim?#

  • Extreme Efficiency: Your hands rarely need to leave the home row.
  • Ubiquitous: Vim is installed on almost every UNIX-like system.
  • Highly Customizable: Can be extended with plugins and scripts.

3. Searching Like a Pro: grep#

grep (Global Regular Expression Print) is a command-line utility for searching plain-text data for lines that match a pattern.

Basic grep Usage#

# Search for the word "error" in a file named logfile.txt
grep "error" logfile.txt
 
# Search for the phrase "connection refused" (case-sensitive)
grep "connection refused" /var/log/syslog

Useful grep Options#

  • -i: Ignore case (case-insensitive search).
    grep -i "warning" logfile.txt
  • -v: Invert match (show lines that do not contain the pattern).
    grep -v "success" results.log  # Show all lines that are not 'success'
  • -n: Show line numbers.
    grep -n "TODO" script.py  # Find all TODOs and show their line numbers
  • -r or -R: Recursively search all files in a directory.
    grep -r "localhost" /etc/  # Search for 'localhost' in all files under /etc/
  • -l: Only show the names of files that contain the match, not the matching lines themselves.
    grep -rl "database_password" /home/project/

Searching in Multiple Files#

# Search in multiple specific files
grep "pattern" file1.txt file2.log
 
# Search in all files with a .conf extension in the current directory
grep "Port" *.conf
 
# Use a wildcard to search in all files
grep -n "function" *

4. Unlocking Precision: Regular Expressions (regexps)#

Regular expressions are patterns used to match character combinations in strings. They turn simple search into a powerful text-manipulation tool.

Basic Regex Metacharacters#

  • . (dot): Matches any single character.
    • a.c matches "abc", "aac", "a5c", etc.
  • \ (backslash): Escapes a special character, allowing you to search for the character itself.
    • file\.txt matches "file.txt" literally (the dot is not a metacharacter here).
  • | (pipe): OR operator.
    • cat|dog matches lines containing "cat" or "dog".

Character Classes#

  • [abc]: Matches any one of the characters a, b, or c.
    • gr[ae]y matches "gray" or "grey".
  • [a-z]: Matches any lowercase letter from a to z.
  • [0-9]: Matches any single digit.
  • [^abc]: Matches any character that is not a, b, or c.

Quantifiers#

  • *: Matches the preceding element zero or more times.
    • ab*c matches "ac", "abc", "abbc", etc.
  • +: Matches the preceding element one or more times.
    • ab+c matches "abc", "abbc", but not "ac".
  • ?: Matches the preceding element zero or one time (makes it optional).
    • colou?r matches both "color" and "colour".
  • {n,m}: Matches the preceding element at least n times, but not more than m times.
    • a{2,4} matches "aa", "aaa", or "aaaa".

Anchors#

  • ^: Matches the beginning of a line.
    • ^Hello matches "Hello" only if it's at the start of a line.
  • $: Matches the end of a line.
    • world!$ matches "world!" only if it's at the end of a line.

Using Regex with grep (-E or egrep)#

By default, grep uses "Basic" regex. For the full power described above, use the -E option or the egrep command.

# Search for lines containing "error" or "warning" (case-insensitive)
grep -E -i "error|warning" logfile.txt
# or
egrep -i "error|warning" logfile.txt
 
# Find IP addresses (simplified pattern)
grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" logfile.txt
 
# Find lines that are empty or contain only whitespace
grep -E "^\s*$" file.txt

Using Regex in Vim Search/Replace#

Vim uses regex by default in its search (/) and replace (:s) commands. The syntax is very similar.

" Search for a word that starts with 'temp'
/temp\w*
 
" Replace all occurrences of 'color' or 'colour' with 'hue'
:%s/colou\?r/hue/g
 
" Delete all lines that are empty or contain only whitespace
:g/^\s*$/d

5. Putting It All Together: Practical Examples#

Example 1: Finding a Configuration Parameter#

Task: Find which configuration file in /etc/ defines the HTTP_PORT.

Solution:

grep -r "HTTP_PORT" /etc/

Example 2: Batch-Renaming Variables in a Script#

Task: Change all occurrences of the variable old_var_name to new_var_name in a Python script script.py.

Solution with Vim:

  1. Open the file: vim script.py
  2. Replace all occurrences with confirmation:
    :%s/old_var_name/new_var_name/gc

Example 3: Analyzing Log Files#

Task: Extract all unique IP addresses that generated a "404 Not Found" error from a web server log access.log.

Solution with grep and regex:

# 1. Find lines with "404"
# 2. Extract the IP address (assuming it's the first field)
# 3. Sort and show only unique IPs
grep "404" access.log | grep -E -o "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | sort | uniq

6. Conclusion#

Mastering Nano, Vim, grep, and regular expressions equips you with a versatile and powerful toolkit for handling text from the command line. Start with Nano for simplicity, then invest time in learning Vim for long-term efficiency. Use grep to quickly find information across files, and unlock its full potential by combining it with regular expressions for precise and complex pattern matching. This skillset is fundamental for anyone working in a terminal environment and will save you countless hours.

7. References & Further Reading#