如何从最新提交中删除文件?


当前回答

同样的问题是,我在本地分支中进行了更改,我只想恢复一个文件。对我有用的是-

(下面的feature/target_branch是我所有更改的地方,包括我想撤消的特定文件的更改)

(origin/feature/target_branch是我要将更改推送到的远程分支)

(feature/stating是我的临时暂存分支,我将从所有需要的更改中推送,不包括对该文件的更改)

从我的原点/feature/target_branch创建本地分支-称为feature/stating将我的工作本地分支feature/target_branch合并到feature/stating分支签出功能/暂存,然后git reset--soft ORIG_HEAD(现在将暂存功能/暂存的所有更改,但未提交。)取消对我以前签入的文件进行不必要的更改将feature/stating的上游分支更改为origin/feature/target_branch提交其余的阶段性更改,并向上游推送到我的远程原点/feature/target_branch

其他回答

如果尚未在服务器上推送更改,则可以使用

git reset --soft HEAD~1

它将重置所有更改并恢复为一次提交

如果您已经推动了更改,请按照@CharlesB回答的步骤操作

Here is the step to remove files from Git Commit.

>git reset --soft HEAD^1(either commitid ) -- now files moved to the staging area.
>git rm --cached filename(it will removed the file from staging area)
>git commit -m 'meaningfull message'(Now commit the required files)

现有的答案都是关于从上次提交中删除不需要的文件。

如果您想从旧提交(甚至推送)中删除不需要的文件,并且不想创建新提交,这是不必要的,因为执行以下操作:

使用查找您希望文件符合的提交;

git-log--图形--装饰--单行

使用签出提交

git checkout<commit_id><path_to_file>

如果要删除许多文件,可以多次执行此操作。

3.

gitcommit-am“删除不需要的文件”

4.

查找错误添加文件的提交的commit_id,让我们在这里说“35c23c2”

git rebase 35c23c2~1-i//注意:“~1”是必需的

此命令根据您的设置打开编辑器。默认值为vim。如果要更改全局git编辑器,请使用;

git-config--全局core.editor<editor_name>

5.

将最后一次提交(应该是“删除不需要的文件”)移动到错误提交的下一行(在我们的例子中是“35c23c2”),并将命令设置为fixup:

pick 35c23c2 the first commit
fixup 0d78b28 remove unwanted files

保存文件后你应该很好。

6.

要完成:

git push-f

如果不幸发生冲突,则必须手动解决。

我将用例子向你解释。设A、B、C为3次连续提交。提交B包含一个不应提交的文件。

git log  # take A commit_id
git rebase -i "A_commit_ID" # do an interactive rebase
change commit to 'e' in rebase vim # means commit will be edited
git rm unwanted_file
git rebase --continue
git push --force-with-lease <branchName>    
git rm  -r ./* --cached

这将删除所有缓存/暂存文件