user624558
user624558

Reputation: 549

Git undo changes to some files while keeping others that involves large number of files

I am using git-bash on Windows. I made a change that affects multiple files (around 500)

Now, the problem is half of the changes should not happen and I need to undo all the changes made to those files. All changes are unstaged changes.

If it involved only few files (10-15) I could simply add the files I need one by one and stash the rest using git stash -u --keep-index. But the number of files involved makes it more difficult to use git add or git checkout -- filename and process each file.

Any suggestion how to handle such a large number of files and either add the ones I need at once or revert the changes for the unwanted files?

Thank you

Upvotes: 0

Views: 76

Answers (1)

Chris
Chris

Reputation: 137179

Probably the easiest way to do what you're trying to do is to leverage the find utility. Note that this is different from Windows' find; if you're using Git bash you should have the correct one available.

Since find can be a bit tricky, I like to make sure that it is giving the results that I expect by echoing out what it will do:

find src/com/mycomp/files -type f -name "*.java" ! -name "*Main.java" -exec echo git checkout -- {} \;

I'll break down the command here:

  • find is the command you're running
  • src/com/mycomp/files is the root directory in which to look
  • -type f says to only consider files, not directories or symlinks
  • -name "*.java" says to look at files ending in .java, but
  • ! -name "*Main.java" says not to include anything ending in Main.java
  • -exec tells find to run the following command on the files it finds
  • echo prints out its arguments, effectively letting us preview our command
  • git checkout -- {} is the commmand that we eventually want to run, with the file names found by find replacing {}
  • and finally, \; says to run the command once for each file, instead of treating all of them together.

If everything looks correct, I edit the command to remove echo and run it again.

Upvotes: 1

Related Questions