如何从git历史记录中的文件中替换文本? [英] How to substitute text from files in git history?

查看:276
本文介绍了如何从git历史记录中的文件中替换文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用基于界面的git客户端(smartGit),因此对git控制台没有多少经验。然而,我现在面对需要从历史记录中替换所有.txt文件中的字符串(因此,不会擦除整个文件,而只是替换字符串)。我发现了以下命令:

  git filter-branch --tree-filter'git ls-files -z* .php | xargs -0 perl -p -i -es#(PASSWORD1 | PASSWORD2 | PASSWORD3)#xXxXxXxXxXx#g' -  --all 

我试过这个,不幸的是,当密码确实被修改时,所有的二进制文件都被破坏了。图像等等都会被破坏。

是否有更好的方法可以做到这一点,不会破坏我的二进制文件?



谢谢。

编辑:

与某事。导致二进制文件损坏的实际代码为:

  $ git filter-branch --tree-filterfind。 - 键入f -exec sed -i -e's / originalpassword / newpassword / g'{} \; 

顶部的代码实际上已经足够奇怪地移除了所有使用我的密码的文件。

解决方案

您可以通过传递 -namepattern来避免触碰不需要的文件 to find



这适用于我:

  git filter-branch --tree-filterfind。-name'* .php'-exec sed -i -e \ 
's / originalpassword / newpassword /G' {} \;


I've always used an interface based git client (smartGit) and thus don't have much experience with the git console.

However, I now face the need to substitute a string in all .txt files from history (so, not erasing the whole file but just substituting a string). I found the following command:

git filter-branch --tree-filter 'git ls-files -z "*.php" |xargs -0 perl -p -i -e "s#(PASSWORD1|PASSWORD2|PASSWORD3)#xXxXxXxXxXx#g"' -- --all

I tried this, and unfortunately noticed that while the password did get changed, all binary files got corrupted. Images, etc. would all be corrupted.

Is there a better way to do this that won't corrupt my binary files?

Thanks.

EDIT:

I got mixed up with something. The actual code that caused binary files to get corrupted was:

$ git filter-branch --tree-filter "find . -type f -exec sed -i -e 's/originalpassword/newpassword/g' {} \;"

The code at the top actually removed all files with my password strangely enough.

解决方案

You can avoid touching undesired files by passing -name "pattern" to find.

This works for me:

git filter-branch --tree-filter "find . -name '*.php' -exec sed -i -e \
    's/originalpassword/newpassword/g' {} \;"

这篇关于如何从git历史记录中的文件中替换文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆