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

我有两个彻底合并的分支。 php

可是,在完成合并以后,我意识到一个文件已经被合并搞砸了(其余人作了自动格式化,gah),而且更容易在另外一个分支中更改成新版本,而且而后从新插入个人一行更改后将其带入个人分支。 git

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


#1楼

使用checkout命令怎么样: spa

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

#2楼

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

git checkout other-branch app/**

至于op的问题,若是你只改变了那里的一个文件,这将很好地工做^ _ ^ rem


#3楼

从您但愿文件结束的分支运行此命令: get

git checkout otherbranch myfile.txt

通用公式: hash

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

一些说明(来自评论): it

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

替代: io

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

#4楼

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

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

git checkout sub_branch file_path/my_file.ext

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


#5楼

请注意,在接受的答案,第一个选项阶段 ,从(像其余分支整个文件git add ...已执行),而第二个选项只是致使复制该文件,但没有舞台的变化(就好像你刚刚手动编辑了文件而且有很大差别)。

从另外一个分支Git复制文件而不进行分段

阶段性变化 (例如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")
相关文章
相关标签/搜索