1

I'd like to copy all files from another git branch matching a certain pattern.

wizzfizz94
  • 1,288
  • 15
  • 20
  • You mean, files that match a given pattern? Like '*.js'? – eftshift0 Apr 03 '19 at 02:22
  • Does this answer your question? [Is there a way to use wildcards with git checkout?](https://stackoverflow.com/questions/15160978/is-there-a-way-to-use-wildcards-with-git-checkout) – qwerty Jul 14 '23 at 15:23

2 Answers2

1

Say you need all js files in all directories. That could be done like this:

git checkout the-other-branch -- '*/*.js'

That will put all those files on the working tree and also on the index ready to be committed, with no relation to the branch that you are checking out from... your branch pointer doesn't move.

eftshift0
  • 26,375
  • 3
  • 36
  • 60
  • Your solution would work for **way** more complex patterns. What I'd probably skip is the while read.... I think it's much better to use an xargs: `git ls-tree -r --name-only | grep | xargs git checkout --` – eftshift0 Apr 03 '19 at 02:29
1

I was able to solve using a bash command i created. First git checkout the branch you wish to copy to then run the following command:

git ls-tree -r --name-only <branch> | grep <pattern> | while read line; do git checkout <branch> -- $line; done

First this lists all files in the source branches directory using git-ls-tree then uses grep to filter only for files that match the Pattern. Then using a while loop reads each line and copys the file across using git checkout.

wizzfizz94
  • 1,288
  • 15
  • 20
  • I think `while read line; do git checkout -- $line; done` could be replaced with `xargs git checkout -- `; this is also a bit faster. – phd Apr 03 '19 at 14:17