Skip to main content

A command-line tool to find and replace text in files using regex patterns.

Project description

License: MIT PyPI version Python 3.10+ Documentation Status

Find and Replace CLI

</code></pre>
<p>A powerful command-line tool for finding and replacing text in files using regular expressions. Built with Python, this tool provides an intuitive interface for bulk text operations across your project files.</p>
<h2>Features</h2>
<ul>
<li><strong>Regular Expression Support</strong>: Use powerful regex patterns for complex search and replace operations</li>
<li><strong>Glob Pattern Matching</strong>: Find files using glob expressions like <code>*.py</code>, <code>config.*</code>, etc.</li>
<li><strong>Recursive Search</strong>: Search through directory trees with the <code>-r/--recursive</code> flag</li>
<li><strong>Interactive Confirmation</strong>: Review matches before making changes (unless using <code>--no-confirm</code>)</li>
<li><strong>Dry Run Mode</strong>: Preview what would be changed without making actual modifications</li>
<li><strong>Colored Output</strong>: Clear, colored terminal output for better readability</li>
<li><strong>Error Handling</strong>: Graceful handling of permission errors, encoding issues, and invalid regex patterns</li>
<li><strong>Cross-Platform</strong>: Works on Windows, macOS, and Linux</li>
</ul>
<h2>Quick Start</h2>
<h3>Installation</h3>
<p>Install from PyPI:</p>
<pre lang="bash"><code>pip install find-replace-cli

Basic Usage

Replace all instances of "old_function" with "new_function" in Python files:

find-and-replace "*.py" /path/to/project "old_function" "new_function"

Common Examples

Replace text in all files recursively:

find-and-replace "*.txt" . "hello.*world" "hi universe" -r

Update version strings in configuration files:

find-and-replace "config.json" ~/projects "\"version\":\s*\"[^\"]*\"" "\"version\": \"2.0.0\"" -r

Dry run to preview changes:

find-and-replace "*.py" . "old_pattern" "new_pattern" --dry-run

No confirmation prompts (automation-friendly):

find-and-replace "*.md" . "old_text" "new_text" -r -n

Use Cases

  • Code Refactoring: Rename functions, variables, or classes across your codebase
  • Configuration Updates: Update configuration values across multiple files
  • Documentation Maintenance: Update links, references, or terminology in documentation
  • Migration Tasks: Update import statements, API calls, or deprecated syntax
  • Bulk Text Processing: Any scenario requiring consistent text changes across multiple files

Safety Features

  • Interactive Confirmation: By default, the tool shows you what will be changed and asks for confirmation
  • Dry Run Mode: Test your patterns without making any changes
  • Detailed Output: See exactly what files were processed and how many matches were found
  • Error Recovery: Continues processing other files even if one file encounters an error

Command Line Arguments

find-and-replace FILE_PATTERN DIRECTORY FIND_PATTERN REPLACE_TEXT [OPTIONS]

Positional Arguments:

  • FILE_PATTERN: Glob pattern for file names (e.g., *.py, config.*)
  • DIRECTORY: Directory to search in
  • FIND_PATTERN: Regular expression pattern to find
  • REPLACE_TEXT: Text to replace matches with (supports regex groups like \1, \2)

Options:

  • -r, --recursive: Search subdirectories recursively
  • -n, --no-confirm: Skip confirmation prompts
  • --dry-run: Show what would be changed without making changes
  • -h, --help: Show help message

Getting Help

License

This project is licensed under the MIT License - see the LICENSE file for details.

Reference

This document provides detailed information about the find-and-replace CLI tool's components and functions.

Command Line Interface

Syntax

find-and-replace FILE_PATTERN DIRECTORY FIND_PATTERN REPLACE_TEXT [OPTIONS]

Arguments

Positional Arguments

FILE_PATTERN : Glob pattern for matching file names : Type: str : Examples: *.py, *.txt, config.*, package.json : Description: Supports standard glob wildcards (*, ?, [...])

DIRECTORY : Directory to search in : Type: str
: Examples: ., /path/to/project, ~/documents : Description: Can be absolute or relative path. Tilde (~) expansion is supported.

FIND_PATTERN : Regular expression pattern to search for : Type: str : Examples: old_function, hello.*world, "version":\s*"[^"]*" : Description: Full Python regex syntax supported. Remember to escape special characters in shell.

REPLACE_TEXT : Replacement text (can include regex groups) : Type: str : Examples: new_function, hi universe, "version": "2.0.0" : Description: Supports backreferences (\1, \2, etc.) for captured groups.

Optional Arguments

-r, --recursive : Search subdirectories recursively : Type: flag : Default: False : Description: When enabled, searches through all subdirectories.

-n, --no-confirm : Skip confirmation prompts : Type: flag : Default: False : Description: Useful for automation scripts. Applies changes without user interaction.

--dry-run : Show what would be changed without making actual changes : Type: flag : Default: False : Description: Safe way to test patterns before applying them.

-h, --help : Show help message and exit : Type: flag

Core Functions

find_files(file_pattern, directory, recursive=False)

Find files matching the pattern in the specified directory.

Parameters:

  • file_pattern (str): Glob pattern for file names
  • directory (str): Directory to search in
  • recursive (bool): Whether to search recursively

Returns:

  • List[str]: List of file paths matching the pattern

Example:

files = find_files("*.py", "/path/to/project", recursive=True)

process_file(file_path, pattern, replacement, no_confirm=False)

Process a single file for find and replace operations.

Parameters:

  • file_path (str): Path to the file to process
  • pattern (str): Regular expression pattern to find
  • replacement (str): Text to replace matches with
  • no_confirm (bool): Whether to skip confirmation prompts

Returns:

  • bool: True if file was modified, False otherwise

Example:

success = process_file("/path/to/file.py", "old_func", "new_func", no_confirm=True)

print_colored(message, color=Colors.NC)

Print message with color formatting.

Parameters:

  • message (str): Message to print
  • color (Colors): Color enum value for formatting

Example:

print_colored("Success!", Colors.GREEN)

Color Constants

Colors Enum

ANSI color codes for terminal output.

Values:

  • Colors.GREEN: Success messages
  • Colors.YELLOW: Warning messages
  • Colors.RED: Error messages
  • Colors.BLUE: Information messages
  • Colors.NC: No color (reset)

Helper Functions

show_matches_for_confirmation(matches, content, replacement)

Display matches and get user confirmation.

Parameters:

  • matches (List): List of regex match objects
  • content (str): File content
  • replacement (str): Replacement text

Returns:

  • bool: True if user confirms, False otherwise

read_file_content(file_path)

Read file content with proper error handling.

Parameters:

  • file_path (str): Path to file

Returns:

  • str: File content, or empty string on error

write_file_content(file_path, content)

Write file content with proper error handling.

Parameters:

  • file_path (str): Path to file
  • content (str): Content to write

Returns:

  • bool: True if successful, False on error

Configuration Functions

create_argument_parser()

Create and configure the argument parser.

Returns:

  • argparse.ArgumentParser: Configured parser object

validate_regex_pattern(pattern)

Validate the regex pattern and exit on error.

Parameters:

  • pattern (str): Regular expression pattern to validate

Raises:

  • SystemExit: If pattern is invalid

Exit Codes

  • 0: Success
  • 1: Invalid regex pattern or other error

Regular Expression Examples

Basic Patterns

  • hello: Matches literal text "hello"
  • hello.*world: Matches "hello" followed by anything, then "world"
  • \d+: Matches one or more digits
  • \w+: Matches one or more word characters

Advanced Patterns

  • "version":\s*"[^"]*": Matches JSON version fields
  • import\s+(\w+): Captures module names in import statements
  • function\s+(\w+)\s*\(: Captures function names

Replacement Examples

  • new_function: Simple text replacement
  • \1_new: Prepend "new_" to captured group 1
  • "version": "2.0.0": Replace with specific version

Error Handling

The tool handles various error conditions gracefully:

  • File not found: Skips missing files with warning
  • Permission denied: Reports permission errors and continues
  • Unicode decode errors: Skips binary files with informative message
  • Invalid regex: Validates patterns before processing
  • Keyboard interrupt: Clean exit on Ctrl+C

Performance Considerations

  • Files are processed sequentially
  • Entire file content is loaded into memory
  • Regex compilation is done once per pattern
  • Large files (>100MB) may cause memory issues

Best Practices

  1. Test with --dry-run before making actual changes
  2. Use version control to track changes
  3. Escape shell metacharacters in patterns
  4. Start with simple patterns and build complexity gradually
  5. Use --no-confirm only for tested, automated scripts

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

find_replace_cli-0.1.1.post2.tar.gz (8.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

find_replace_cli-0.1.1.post2-py3-none-any.whl (9.1 kB view details)

Uploaded Python 3

File details

Details for the file find_replace_cli-0.1.1.post2.tar.gz.

File metadata

  • Download URL: find_replace_cli-0.1.1.post2.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.13.5 Linux/6.11.0-1018-azure

File hashes

Hashes for find_replace_cli-0.1.1.post2.tar.gz
Algorithm Hash digest
SHA256 2df4289e2c0d58d3714a59b42c7a4ccd6fc752497717f660db2872f108bc2073
MD5 7a59c72bb15de7ecdde00f3301e5a74f
BLAKE2b-256 145ad144f157e4a86d14bbd56e7198594064ae779144f16af97988ea97c07eba

See more details on using hashes here.

File details

Details for the file find_replace_cli-0.1.1.post2-py3-none-any.whl.

File metadata

File hashes

Hashes for find_replace_cli-0.1.1.post2-py3-none-any.whl
Algorithm Hash digest
SHA256 4ed0ac876c6e75d5d4d51cdacbaa21bcc72a8603463a85cd6e43d1794fcba34c
MD5 7ab07f0ea76433af7bf84b0e6e7af5c2
BLAKE2b-256 0a13722e40eded224784b397eb6529c1e5a14dd1a83de567036dafc975a58031

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page