Removing multiple files from a Git repo that have

2019-01-01 09:37发布

I have a Git repo that I have deleted four files from using rm (not git rm), and my Git status looks like this:

#    deleted:    file1.txt
#    deleted:    file2.txt
#    deleted:    file3.txt
#    deleted:    file4.txt

How do I remove these files from Git without having to manually go through and add each file like this:

git rm file1 file2 file3 file4

Ideally, I'm looking for something that works in the same way that git add . does, if that's possible.

29条回答
浅入江南
2楼-- · 2019-01-01 09:51

None of the flags to git-add will only stage removed files; if all you have modified are deleted files, then you're fine, but otherwise, you need to run git-status and parse the output.

Working off of Jeremy's answer, this is what I got:

git status |  sed -s "s/^.*deleted: //" | grep "\(\#\|commit\)" -v | xargs git rm
  1. Get status of files.
  2. For deleted files, isolate the name of the file.
  3. Remove all the lines that start with #s, as well as a status line that had the word "deleted" in it; I don't remember what it was, exactly, and it's not there any longer, so you may have to modify this for different situations. I think grouping of expressions might be a GNU-specific feature, so if you're not using gnutils, you may have to add multiple grep -v lines.
  4. Pass the files to git rm.

Sticking this in a shell alias now...

查看更多
萌妹纸的霸气范
3楼-- · 2019-01-01 09:51

As mentioned

git add -u

stages the removed files for deletion, BUT ALSO modified files for update.

To unstage the modified files you can do

git reset HEAD <path>

if you like to keep your commits organized and clean.
NOTE: This could also unstage the deleted files, so careful with those wildcards.

查看更多
牵手、夕阳
4楼-- · 2019-01-01 09:51
git rm $(git ls-files -d)

Removes all files listed by the git ls-files command (-d show only deleted files). Doesn't work for files with spaces in the filename or path, but simple to remember

查看更多
萌妹纸的霸气范
5楼-- · 2019-01-01 09:52
git commit -m 'commit msg' $(git ls-files --deleted)

This worked for me after I had already deleted the files.

查看更多
像晚风撩人
6楼-- · 2019-01-01 09:53

The following will work, even if you have a lot of files to process:

git ls-files --deleted | xargs git rm

You'll probably also want to commit with a comment.

For details, see: Useful Git Scripts

查看更多
ら面具成の殇う
7楼-- · 2019-01-01 09:53

(Yet another variation)

I wanted to delete all the already deleted from the disk files but from one specific folder, leaving the other folders untouched. The following worked for me:

git ls-files --deleted  | grep <folder-name> | xargs git rm
查看更多
登录 后发表回答