LinuxCommandLibrary

git-sed

Apply sed across Git repository revisions

TLDR

Replace the specified text in the current repository

$ git sed '[find_text]' '[replace_text]'
copy

Replace the specified text and then commit the resulting changes with a standard commit message
$ git sed -c '[find_text]' '[replace_text]'
copy

Replace the specified text, using regex
$ git sed -f g '[find_text]' '[replace_text]'
copy

Replace a specific text in all files under a given directory
$ git sed '[find_text]' '[replace_text]' -- [path/to/directory]
copy

SYNOPSIS

git-sed [sed-options...] '<sed-expression>' [<pathspec>...]

PARAMETERS

-i[EXT]
    edit files in-place (backup with EXT if given) and git add changes

-E / -r / -R
    use extended regular expressions

-n
    suppress automatic printing of pattern space

-e SCRIPT
    append/execute sed SCRIPT

-f SCRIPT-FILE
    read sed scripts from SCRIPT-FILE

<PATHSPEC>
    limit to files matching Git pathspec

DESCRIPTION

git-sed is a utility that extends sed's search-and-replace capabilities to Git repositories. It targets only files tracked by Git (via git ls-files), applies sed expressions, and optionally edits files in-place while staging changes with git add. This prevents accidental modifications to untracked or ignored files, making it safer for repo-wide refactoring.

Key benefits include previewing changes without editing (omit -i), support for standard sed syntax like BRE/ERE regex, and pathspec limiting. It's ideal for renaming variables, updating imports, or fixing strings across projects. Multiple sed scripts can be chained with -e. Backups are created if -i specifies an extension (e.g., -i.bak).

Unlike raw sed + xargs, it integrates seamlessly with Git workflows, reducing errors in large codebases.

CAVEATS

Operates only on tracked files (use --cached or variants for staged/untracked if supported); preview without -i to avoid mistakes; backups may pollute repo if EXT used carelessly; not core Git—install separately.

PREVIEW EXAMPLE

git sed 's/foo/bar/g' src/**/*.js
Shows changes without editing.

IN-PLACE EXAMPLE

git sed -i 's/old/new/g' '*.py'
Replaces, edits, stages Python files.

HISTORY

Originated as community shell/Ruby scripts in early 2010s (e.g., GitHub repos by romainl, martanne); gained popularity for safe repo refactors amid growing monorepos; multiple forks exist, often packaged in distros or via npm/gem.

SEE ALSO

sed(1), git-ls-files(1), git-add(1), xargs(1)

Copied to clipboard