如何将单个文件的版本从一个git分支复制到另一个git分支?

问题描述 投票:816回答:6

我有两个完全合并的分支。

但是,在完成合并之后,我意识到一个文件已经被合并搞砸了(其他人做了自动格式化,gah),并且更容易在另一个分支中更改为新版本,并且然后重新插入我的一行更改后将其带入我的分支。

那么git中最简单的方法是什么呢?

git git-branch branching-and-merging
6个回答
1535
投票

从您希望文件结束的分支运行此命令:

git checkout otherbranch myfile.txt

通用公式:

git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>

一些说明(来自评论):

  • 使用提交哈希,您可以从任何提交中提取文件
  • 这适用于文件和目录
  • 覆盖文件myfile.txtmydir
  • 通配符不起作用,但相对路径可行
  • 可以指定多个路径

替代:

git show commit_id:path/to/file > path/to/file

76
投票

我在类似的搜索中结束了这个问题。在我的情况下,我希望从另一个分支中提取一个文件到当前工作目录,该目录与文件的原始位置不同。 Answer

git show TREEISH:path/to/file >path/to/local/file

50
投票

使用checkout命令怎么样:

  git diff --stat "$branch"
  git checkout --merge "$branch" "$file"
  git diff --stat "$branch"

13
投票

根据madlep的回答,您还可以使用目录blob从另一个分支复制一个目录。

git checkout other-branch app/**

至于op的问题,如果你只改变了那里的一个文件,这将很好地工作^ _ ^


12
投票

1)确保您在需要文件副本的分支机构中。例如:我想在master中使用子分支文件,因此你需要签出或者应该在master git checkout master

2)现在单独检查你想要从子分支到master的特定文件,

git checkout sub_branch file_path/my_file.ext

这里sub_branch表示你有文件后跟你需要复制的文件名。


1
投票

请注意,在接受的答案中,第一个选项将整个文件从另一个分支中分段(如git add ...已执行),第二个选项只会导致复制文件,但不会进行更改(就像您刚刚手动编辑了文件并且有很大差异)。

Git copy file from another branch without staging it

变化上演(例如git add filename)

$ git checkout directory/somefile.php feature-B

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   directory/somefile.php

未完成的变更(未上演或已提交):

$ git show feature-B:directory/somefile.php > directory/somefile.php

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   directory/somefile.php

no changes added to commit (use "git add" and/or "git commit -a")
© www.soinside.com 2019 - 2024. All rights reserved.