如何从给定提交中记录的文件中仅恢复几行?

doc*_*_id 19 git git-checkout

我想从旧提交中记录的文件中恢复几行.我可以通过跑步看到那些线条

git log -p
Run Code Online (Sandbox Code Playgroud)

作为最后的手段,我准备简单地从该日志的输出中复制那些行,但这会伤害我的纯粹主义者的心脏,而且看起来相当不专业.

我不希望简单地运行git checkout <file>,因为这将放弃对了本地修改<file>,因为提交的问题.相反,我想<file>仅使用纯Git命令将来自该提交的更改合并到工作树中.

我怎样才能做到这一点?

jub*_*0bs 17

使用互动结帐

以下git-checkout语法,

git checkout --patch <tree-ish> -- <paths>
Run Code Online (Sandbox Code Playgroud)

或者,等效地,

git checkout -p <tree-ish> -- <paths>
Run Code Online (Sandbox Code Playgroud)

允许您以交互方式检查列出的一个或多个文件<paths>中的数据库<tree-ish>(最常见的是提交).

有关更多详细信息,请参见git-checkout手册页.

例

为了解决问题,这里有一个玩具示例(省略了无关的stdout):

# set things up
$ mkdir test
$ cd test
$ git init

# create some content and commit
$ printf "Hello, world.\n" > README.md
$ printf "foo\nbar\nbaz\n" > test.txt
$ git add .
$ git commit -m "initial commit"

# modify the working tree
$ printf "another line\n" >> README.md 
$ printf "foo\nfoo\n" > test.txt

# now restore stuff from test.txt as recorded in master's tip
$ git checkout -p master -- test.txt
diff --git b/test.txt a/test.txt
index 0d55bed..86e041d 100644
--- b/test.txt
+++ a/test.txt
@@ -1,2 +1,3 @@
 foo
-foo
+bar
+baz
Apply this hunk to index and worktree [y,n,q,a,d,/,e,?]? y
error: patch failed: test.txt:1
error: test.txt: patch does not apply
The selected hunks do not apply to the index!
Apply them to the worktree anyway? y

# Sanity check: inspect the working tree
# (the hunk "bar\nbaz" from test.txt was restored, as desired)
$ cat test.txt
foo
bar
baz
# (README.md, on the other hand, was not affected, as desired)
$ cat README.md
Hello, world.
another line
Run Code Online (Sandbox Code Playgroud)