87

When I do a git status, I see files like this:

modified:  dir/A/file.txt
modified:  dir/B/file.txt
modified:  dir/C/file.txt
modified:  dir/D/file.txt

What I want to do is to discard changes to all files EXCEPT for dir/C/file.txt

I want to do something like this:

git checkout -- dir/!C/file.txt

2 Answers 2

164
git add dir/C/file.txt # this file will stay modified and staged
git checkout .

If you want to unstage the file after that:

git reset
2
  • 3
    ABSOLUTELY BRILLIANT Commented Apr 16, 2020 at 0:09
  • git clean -df - is helpful if you have a dirty folder Commented Jun 7, 2021 at 20:24
1

There is a secret single line command for it:

git checkout -- $(git diff --name-only | grep -v "path/to/your/file")

For multiple files:

git checkout -- $(git diff --name-only | grep -E -v "file1|file2|file3")
1
  • I'm still a bit impressed as to why this post is not upvoted. Commented May 10 at 12:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.