Skip to content

Commit 629d8b7

Browse files
committed
Add Replace Pattern Across Many Files In A Project as a Unix TIL
1 parent 746957c commit 629d8b7

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1301 TILs and counting..._
13+
_1302 TILs and counting..._
1414

1515
---
1616

@@ -1296,6 +1296,7 @@ _1301 TILs and counting..._
12961296
- [Provide A Fallback Value For Unset Parameter](unix/provide-a-fallback-value-for-unset-parameter.md)
12971297
- [Remove A Directory Called `-p`](unix/remove-a-directory-called-dash-p.md)
12981298
- [Repeat Yourself](unix/repeat-yourself.md)
1299+
- [Replace Pattern Across Many Files In A Project](unix/replace-pattern-across-many-files-in-a-project.md)
12991300
- [Run A Command Repeatedly Several Times](unix/run-a-command-repeatedly-several-times.md)
13001301
- [Safely Edit The Sudoers File With Vim](unix/safely-edit-the-sudoers-file-with-vim.md)
13011302
- [Saying Yes](unix/saying-yes.md)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Replace Pattern Across Many Files In A Project
2+
3+
Let's say I have a bunch of files in the `db/migrate` directory of my project
4+
that contain a line of text I'd like to update. I want to replace all
5+
occurrences of `t.bigint` with `t.integer`.
6+
7+
First, I can get an idea of the scope of the change by listing out all the
8+
files and lines where this pattern exists using
9+
[`ripgrep`](https://github.com/BurntSushi/ripgrep).
10+
11+
```bash
12+
$ rg 't.bigint' db/migrate
13+
```
14+
15+
I can visually do a quick scan to make sure I'm not picking up results with my
16+
pattern that weren't intended.
17+
18+
Then, I can include the `--files-with-matches` flag to limit the `ripgrep`
19+
output to just filenames. Those filenames can be piped to `sed` (via `xargs`)
20+
which will do the pattern replacement.
21+
22+
```bash
23+
$ rg --files-with-matches 't.bigint' db/migrate | \
24+
xargs sed -i '' 's/t.bigint/t.integer/g'
25+
```
26+
27+
This does an in-place (`-i ''`) edit of the files substituting (`s///g`)
28+
globally the occurrences of `t.bigint` for `t.integer`.

0 commit comments

Comments
 (0)