如何将单个文件的版本从一个 git 分支复制到另一个?
-
08-07-2019 - |
题
我有两个完全合并在一起的分支。
然而,合并完成后,我意识到一个文件被合并弄乱了(其他人做了自动格式化,啊),并且在另一个分支中更改为新版本会更容易,并且然后将其引入我的分支后重新插入我的一行更改。
那么 git 中最简单的方法是什么?
解决方案
从您希望文件结束的分支运行此命令:
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.txt
和mydir
- 通配符不起作用,但相对路径可以
- 可以指定多个路径
替代:
git show commit_id:path/to/file > path/to/file
其他提示
我在类似的搜索中结束了这个问题。在我的情况下,我希望从另一个分支中提取一个文件到当前工作目录,该目录与文件的原始位置不同。 回答:
git show TREEISH:path/to/file >path/to/local/file
使用checkout命令怎么样:
git diff --stat "$branch"
git checkout --merge "$branch" "$file"
git diff --stat "$branch"
按照madlep的回答,您也可以使用目录blob从另一个分支复制一个目录。
git checkout other-branch app/**
关于op的问题,如果你只更改了那里的一个文件,这将很好用^ _ ^
1)确保您在需要文件副本的分支机构中。
例如:我想在master中使用子分支文件,因此您需要签出或者应该在master git checkout master
2)现在单独检查您希望从子分支到主服务器的特定文件,
git checkout sub_branch file_path/my_file.ext
此处sub_branch
表示您拥有该文件的位置,后跟您需要复制的文件名。
请注意,在接受的答案中,第一个选项阶段来自另一个分支的整个文件(如git add ...
已执行),并且第二个选项只会导致复制文件,但不会进行更改(就好像您刚刚手动编辑了文件并且有明显的差异)。
分阶段变化(例如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")
不隶属于 StackOverflow