Is there a way to use wildcards with git checkout?

前端 未结 8 850
遇见更好的自我
遇见更好的自我 2020-12-24 00:40

What I would like to do is to checkout a single file or a set of files with a common name part like this

git checkout myBranch */myFile.md and

<

相关标签:
8条回答
  • 2020-12-24 01:01

    Windows git bash with xargs

    git difftool myBranch --name-only *.java | xargs git checkout myBranch
    
    0 讨论(0)
  • 2020-12-24 01:02

    Git does deal with wildcards, using fnmatch(3). See the pathspec entry in Git glossary.

    But to be sure that git can see the wildcards, they must be escaped otherwise your shell will expand them first. Typically, I use wildcards between single-quotes:

    git checkout myBranch -- '*/myFile.md'
    

    The wildcards are applied to the whole name, directories included.

    As you can see in the documentation, the pathspec also allows magic signature which change how to interpret the pathspec. For example, you can have case-insensitive paths with icase (you can type ':(icase)*readme*' to find all your readme's).

    I quote @bambams's comment here, in case you have problems in Windows:

    This is not working for me in Windows with 2.8.1.windows.1 and I'm utilizing Git from the cmd.exe shell so no globbing built in. There is however a solution if you're in such a sorry state. Combine git diff --name-only and xargs to achieve your goal:

    git diff --name-only <COMMIT> -- <GLOB>... | xargs git checkout <COMMIT> 
    
    0 讨论(0)
  • 2020-12-24 01:02

    Git does not deal with the wildcard, but your shell does.

    Try this :

    git checkout myBranch **/myFile.md
    

    and

    git checkout myBranch  **/*Test*
    

    With the **, your shell will look for files in all the subdirectories starting from the current working directory.

    0 讨论(0)
  • 2020-12-24 01:03

    Knowing that git returns branch list names from 3rd char, one can just switch to needed branch defined via [mask]:

    BRANCH_NAME=$(git branch --list | grep [mask] | cut -c3-)
    git checkout ${BRANCH_NAME}
    
    0 讨论(0)
  • 2020-12-24 01:05

    If you have a gitignore or untracked files and you want to use wildcards with git checkout, then it might give you problems, and a solution could be:

    git ls-files '*/myFile.md' | tr '\n' '\0' | xargs -0 -L1 -I '$' git checkout -- '$'
    
    0 讨论(0)
  • 2020-12-24 01:08

    Powershell

    @(gci -Recurse *test* | Resolve-Path -Relative) | %{git checkout mybranch -- $_)
    

    gci generates a list of all files matching the criteria (*test*) then pipes it to Resolve-Path to get the relative path. Finally the flattened (@) list of filenames is piped into the git invokation (executes once per file found).

    0 讨论(0)
提交回复
热议问题