From 629d8b7f7bc907ffca3217676e262ba79fc9f714 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 12 May 2023 10:42:13 -0500 Subject: [PATCH] Add Replace Pattern Across Many Files In A Project as a Unix TIL --- README.md | 3 +- ...-pattern-across-many-files-in-a-project.md | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 unix/replace-pattern-across-many-files-in-a-project.md diff --git a/README.md b/README.md index dde9cfe..eddf31c 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/unix/replace-pattern-across-many-files-in-a-project.md b/unix/replace-pattern-across-many-files-in-a-project.md new file mode 100644 index 0000000..e3c697a --- /dev/null +++ b/unix/replace-pattern-across-many-files-in-a-project.md @@ -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`.