1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Replace Pattern Across Many Files In A Project as a Unix TIL

This commit is contained in:
jbranchaud
2023-05-12 10:42:13 -05:00
parent 746957ca75
commit 629d8b7f7b
2 changed files with 30 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1301 TILs and counting..._
_1302 TILs and counting..._
---
@@ -1296,6 +1296,7 @@ _1301 TILs and counting..._
- [Provide A Fallback Value For Unset Parameter](unix/provide-a-fallback-value-for-unset-parameter.md)
- [Remove A Directory Called `-p`](unix/remove-a-directory-called-dash-p.md)
- [Repeat Yourself](unix/repeat-yourself.md)
- [Replace Pattern Across Many Files In A Project](unix/replace-pattern-across-many-files-in-a-project.md)
- [Run A Command Repeatedly Several Times](unix/run-a-command-repeatedly-several-times.md)
- [Safely Edit The Sudoers File With Vim](unix/safely-edit-the-sudoers-file-with-vim.md)
- [Saying Yes](unix/saying-yes.md)

View File

@@ -0,0 +1,28 @@
# Replace Pattern Across Many Files In A Project
Let's say I have a bunch of files in the `db/migrate` directory of my project
that contain a line of text I'd like to update. I want to replace all
occurrences of `t.bigint` with `t.integer`.
First, I can get an idea of the scope of the change by listing out all the
files and lines where this pattern exists using
[`ripgrep`](https://github.com/BurntSushi/ripgrep).
```bash
$ rg 't.bigint' db/migrate
```
I can visually do a quick scan to make sure I'm not picking up results with my
pattern that weren't intended.
Then, I can include the `--files-with-matches` flag to limit the `ripgrep`
output to just filenames. Those filenames can be piped to `sed` (via `xargs`)
which will do the pattern replacement.
```bash
$ rg --files-with-matches 't.bigint' db/migrate | \
xargs sed -i '' 's/t.bigint/t.integer/g'
```
This does an in-place (`-i ''`) edit of the files substituting (`s///g`)
globally the occurrences of `t.bigint` for `t.integer`.