โ† Back to DevBytes

Sublime Text Find and Replace: Complete Guide

Sublime Text Find and Replace: Complete Guide

Sublime Text is one of the most popular code editors among developers, and its Find and Replace functionality is among the most powerful features it offers. Whether you are refactoring a large codebase, fixing a recurring typo, or performing complex multi-file transformations, mastering Find and Replace in Sublime Text will dramatically improve your productivity. This guide covers everything from basic usage to advanced regular expressions, multi-file operations, and best practices.

What Is Find and Replace in Sublime Text?

Find and Replace is a core editing feature that allows you to search for text patterns within a file or across an entire project and substitute them with new text. Sublime Text enhances this basic concept with support for regular expressions, case sensitivity, whole-word matching, multi-cursor selection, and project-wide search. These capabilities make it an indispensable tool for developers who need to manipulate code quickly and accurately.

Why Find and Replace Matters

Manual editing is error-prone and time-consuming, especially in large projects. Find and Replace automates repetitive text transformations, ensuring consistency across your codebase. It is essential for tasks such as renaming variables, updating API endpoints, migrating configuration formats, and applying bulk formatting changes. When combined with regular expressions, it becomes a mini text-processing engine built directly into your editor.

Basic Find and Replace

Opening the Find Panel

The fastest way to access Find and Replace is through keyboard shortcuts. Sublime Text provides separate panels for single-file and multi-file operations.

Performing a Simple Replacement

To replace text within the current file, open the Replace panel using Ctrl+H. Type the text you want to find in the "Find" field and the replacement text in the "Replace" field. You can then choose to replace occurrences one at a time or all at once.

For example, suppose you have the following JavaScript snippet and want to rename a variable from userName to userFullName:

function greet(userName) {
  console.log("Hello, " + userName);
  return userName.toUpperCase();
}

After opening the Replace panel, enter userName in Find and userFullName in Replace, then press Ctrl+Alt+Enter. The result will be:

function greet(userFullName) {
  console.log("Hello, " + userFullName);
  return userFullName.toUpperCase();
}

Search Options and Toggles

Sublime Text provides several toggle buttons in the Find and Replace panel that refine how searches are performed. Understanding these options is critical for accurate replacements.

These toggles can be combined. For instance, enabling both Case Sensitive and Whole Word ensures that searching for id will not match userId or ID.

Regular Expressions in Find and Replace

Enabling Regex Mode

Click the .* button in the Find panel or press Alt+R to enable regular expression mode. Sublime Text uses the Boost regex engine, which supports a wide range of pattern syntax including capture groups, lookaheads, and character classes.

Capture Groups and Backreferences

One of the most powerful regex features in Find and Replace is the ability to capture parts of the matched text and reuse them in the replacement. Parentheses create capture groups, and you reference them in the replacement string using $1, $2, and so on.

Suppose you have a list of configuration keys in the format key=value and you want to convert them to JSON format:

host=localhost
port=8080
debug=true

Use the following Find pattern:

(\w+)=(\w+)

And the following Replace pattern:

"$1": "$2",

The result will be:

"host": "localhost",
"port": "8080",
"debug": "true",

Common Regex Patterns

Here are some practical regex patterns developers frequently use:

Swapping Two Values

You can use capture groups to swap values. For example, if you have CSS declarations where padding values need to be swapped:

padding: 10px 20px;

Find pattern:

padding: (\d+)px (\d+)px;

Replace pattern:

padding: $2px $1px;

Result:

padding: 20px 10px;

Find in Files: Project-Wide Search and Replace

Using Find in Files

Press Ctrl+Shift+F to open the Find in Files panel. This panel allows you to search across your entire project, specific folders, or files matching certain patterns. The results are displayed in a dedicated output panel where you can click each result to navigate to the corresponding location.

The Find in Files panel includes three additional fields:

Filtering with File Patterns

The Where field supports glob patterns to include or exclude files. Here are some examples:

For example, to search for the string TODO in all TypeScript files while excluding test files, you would enter the following in the Where field:

*.ts, -*.test.ts

Replacing Across Files

To perform a project-wide replacement, enter your Find and Replace text in the Find in Files panel, set the Where filter, then click the Replace button on the right side of the panel. Sublime Text will apply the replacement to all matching files. Each modified file will appear with an unsaved indicator, allowing you to review changes before saving.

It is strongly recommended to review the search results in the output panel before clicking Replace. You can double-click any result to open the file at the matching line and verify the context.

Multi-Cursor Find and Replace

Sublime Text is famous for its multi-cursor editing, which can be combined with Find and Replace for powerful inline transformations. After performing a Find operation, press Ctrl+D (Windows/Linux) or Cmd+D (Mac) to select the next occurrence of the search term and add a cursor at each location. You can then type replacement text, and it will be applied at all cursor positions simultaneously.

To select all occurrences at once, press Alt+F3 (Windows/Linux) or Ctrl+Cmd+G (Mac). This is useful when you want to edit every instance of a term in the current file without using the Replace panel.

For example, consider the following code:

const data = fetch('/api/data');
const user = fetch('/api/user');
const config = fetch('/api/config');

If you place your cursor on fetch and press Alt+F3, all three instances will be selected. Typing axios.get will replace all of them at once:

const data = axios.get('/api/data');
const user = axios.get('/api/user');
const config = axios.get('/api/config');

Search and Replace in Selection

Sometimes you only want to replace text within a specific portion of a file. Sublime Text supports this through the In Selection toggle. Select the text you want to search within, open the Find or Replace panel, and enable the In Selection option by clicking the icon or pressing Alt+A. The search will be confined to the selected region.

This is particularly useful when working with large files where a global replacement might affect code outside the area you intend to modify.

Incremental Search

Sublime Text supports incremental search, where results are highlighted as you type. When you open the Find panel and start typing, the editor highlights all matches in the current file and scrolls to the first one. Pressing Enter moves to the next match. This provides immediate feedback and helps you refine your search pattern before committing to a replacement.

Best Practices

Always Preview Before Replacing All

Before pressing Replace All, review the highlighted matches in the file or the results in the Find in Files output panel. This helps you catch unintended matches, especially when using regular expressions that may match more text than expected.

Use Version Control as a Safety Net

Even with careful previewing, bulk replacements can introduce errors. Always commit your current work to version control before performing large-scale Find and Replace operations. This allows you to easily revert changes if something goes wrong.

Start Specific, Then Broaden

When constructing a regex pattern, start with a specific pattern and test it on a small sample. Once you confirm it matches exactly what you intend, broaden the scope to the entire file or project. This iterative approach prevents accidental widespread changes.

Leverage Whole Word and Case Sensitivity

When renaming variables or functions, enable Whole Word and Case Sensitive toggles to avoid replacing substrings inside unrelated identifiers. For example, replacing id without Whole Word enabled would also modify userId, hidden, and valid.

Use File Filters to Narrow Scope

In Find in Files, always specify a Where filter to limit the search to relevant files. Searching the entire project without filters can produce thousands of matches in dependencies, build artifacts, and minified files, making it difficult to identify the changes that matter.

Save Complex Regex Patterns

If you frequently use the same complex regex patterns, consider saving them in a snippets file or a notes document. Sublime Text also supports plugins that can store and recall frequently used search patterns, further streamlining your workflow.

Combine with Multi-Cursor for Surgical Edits

For replacements that require slight variations at each location, use Ctrl+D to select occurrences one at a time and edit them individually with multiple cursors. This gives you fine-grained control that a blanket Replace All cannot provide.

Conclusion

Find and Replace in Sublime Text is far more than a simple text substitution tool. With support for regular expressions, project-wide search, file pattern filtering, multi-cursor editing, and scoped selections, it provides a robust toolkit for managing code at any scale. By understanding the available options, practicing careful preview habits, and combining features strategically, you can perform complex refactoring tasks with speed and confidence. Whether you are fixing a single typo or migrating an entire codebase, mastering these techniques will make you a significantly more efficient developer.

๐Ÿ›  Tools from DevBytes

Inventory Tracker Pro โ€” Excel inventory system, low-stock alerts ยท $19
AI Dev Kit for Mac โ€” local AI dev environment templates ยท $9.99
KeyMapper for Mac โ€” custom keyboard shortcut toolkit ยท $7.99

โ† Back to all articles