如何替换整个主目录中字符串的所有实例?

How can I replace all instances of a string in my entire home directory?

我正在做一个图书馆,我做了一个重大的改变。我所有的项目都导入 github.com/retep-mathwizard/utils/src/...,但我已将我的项目缩短为 github.com/retep-mathwizard/utils/...。我需要从 ~ 开始找到它的每一次出现,并替换所有出现的地方。有办法吗?

sed是你的朋友。

$ sed -i 's_github.com/retep-mathwizard/utils/src_github.com/retep-mathwizard/utils_g' *.txt

其中 *.txt 是您想要 search/replace 的任何文本文件。请注意 _ 很重要。它用于分隔搜索和替换中的模式,因为您的模式中既有标准的 / 分隔符,也有常用的替代 --i.bak 选项将告诉 sed 就地编辑文件,并保存扩展名为 .bak.

的备份副本

如果文件位于许多子目录中,您需要使用 findxargs.

这样的组合
$ find ~ -name "*.txt" -print0 | xargs -0 sed -i.bak 's_github.com/retep-mathwizard/utils/src_github.com/retep-mathwizard/utils_g' 

同样,*.txt 是任何正则表达式只会找到您想要替换文本的文件。

免责声明:与任何涉及这些工具的东西一样,您应该先在可替换的东西上或在新的 git 分支中尝试。

编辑:删除了 -i 标志上的扩展。正如评论中指出的那样,一切都在源代码管理之下,因此在不保存备份文件的情况下进行就地编辑应该没问题。

此命令查找主目录中的所有文件,减去 .git 文件夹中的文件:

find ~ -type d -name '.git' -prune -o -type f -print

要用其他东西替换某物的所有实例,我们可以使用 sed:

sed 's|\(github\.com/retep-mathwizard/utils/\)src/||g' filename

这会捕获我们想要保留的部分并在替换中使用它。

结合这些命令遍历所有文件,使用 -i 标志进行就地编辑(对 BSD sed 使用 -i '' / Mac OS) – 我们将 -print 操作替换为 -exec sed:

find ~ -type d -name '.git' -prune -o -type f \
-exec sed 's|\(github\.com/retep-mathwizard/utils/\)src/||g' {} \;