Say I am trying to checkout a certain set of git file, e.g. app/*^(.tmpl).html
,
how to throw this regex into git checkout branch -- (regex)
You probably knew that a branch can be "checked out" with the command git checkout <branch-name> , but interestingly enough, a single file or a whole folder can also be checked out from another branch.
Git checkout works hand-in-hand with git branch . The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch . Once created you can then use git checkout new_branch to switch to that branch.
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
.
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:
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-1035Those 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With