how to use regex in git checkout command to specify file subsets
Just updating this answer but I was able to git checkout
with a wildcard so I believe this is possible now. I am running git version 1.9.3.
I'm using such combination of commands.
In case you need remote branch:
git checkout $(git branch -a | grep "your-key-words-here" | grep remotes)
And in case you need only local branch:
git checkout $(git branch | grep "your-key-words-here")
Example of usage
Mainly developers names branch by task number from JIRA or whatever, so using those commands you can faster switch to branch that you need.
(1) All available local branches:
- feature/CAN2-1035_new_calculation_for_internal_transfer
- feature/CAN2-921_new_ui
- develop (current)
To switch on feature/CAN2-1035_new_calculation_for_internal_transfer
branch, you should enter command:
git checkout $(git branch | grep CAN2-1035)
git branch
- will return all local branches (1)grep CAN2-1035
- will filter result of (1) and return only those that contains CAN2-1035
Those commands also could be extracted to some bash command to simplify usage.
Git's pathspec specials are poorly advertised, but they're quite capable:
git checkout ':!*.tmpl.*' app/\*.html
As mentioned in "Is there a way to use wildcards with git checkout
?"
Git does not deal with the wildcard, but your shell does.
As noted below, you would need to escape the wildcard character in order for git to interpret it: afile\*
, or use simple quotes.
The example section of git checkout
shows a wildcard usage:
rm hello.c
git checkout -- '*.c'
Note the quotes around
*.c
.
The filehello.c
will also be checked out, even though it is no longer in the working tree, because the file globbing is used to match entries in the index (not in the working tree by the shell).
An alternative, for instance, would be to use find (as in "“git add *.js
” did not add the files in sub-directories")
find . -name '*js' -exec git checkout {} \;
You can try your regex with find -regex
For instance, Tukaz uses (from the comments):
find ./packages/* -maxdepth 1 -name 'package.json' \ -exec git checkout {} \;
in order to checkout only the
package.json
of each project I have and omitdist
ornodemodules
sub-folders.
The more modern command (since 2014) would be the Git 2.23+ (Q3 2019) git restore
:
git restore -s=aBranch -- '*.c'
With '*.c' following the glob pattern described in pathspec
.