我如何递归地通过位于不同目录的模式(或glob)添加文件?

例如,我想用一个命令添加A/B/C/foo.java和D/E/F/bar.java(以及其他几个java文件):

git add '*.java'

不幸的是,这并没有像预期的那样起作用。


当前回答

如果您已经在跟踪文件并对其进行了更改,现在您想根据模式有选择地添加它们,您可以使用——modified标志

git ls-files --modified | grep '<pattern>' | xargs git add

例如,如果您只想将CSS更改添加到此提交,您可以这样做

git ls-files --modified | grep '\.css$' | xargs git add

更多标志请参见man git-ls-files

其他回答

正如在“git:如何递归地添加匹配glob模式的目录子树中的所有文件?”中提到的,如果你正确地转义或引用你的路径spec通配符(如'*.java'),那么是的,git添加'*.java'

Git 2.13(2017年第二季度)改进了交互式添加:

参见Jeff King (peff)的commit 7288e12(2017年3月14日)。 (由Junio C Hamano合并- gitster -在commit 153e0d7, 2017年3月17日)

add --interactive: do not expand pathspecs with ls-files When we want to get the list of modified files, we first expand any user-provided pathspecs with "ls-files", and then feed the resulting list of paths as arguments to "diff-index" and "diff-files". If your pathspec expands into a large number of paths, you may run into one of two problems: The OS may complain about the size of the argument list, and refuse to run. For example: $ (ulimit -s 128 && git add -p drivers) Can't exec "git": Argument list too long at .../git-add--interactive line 177. Died at .../git-add--interactive line 177. That's on the linux.git repository, which has about 20K files in the "drivers" directory (none of them modified in this case). The "ulimit -s" trick is necessary to show the problem on Linux even for such a gigantic set of paths. Other operating systems have much smaller limits (e.g., a real-world case was seen with only 5K files on OS X). Even when it does work, it's really slow. The pathspec code is not optimized for huge numbers of paths. Here's the same case without the ulimit: $ time git add -p drivers No changes. real 0m16.559s user 0m53.140s sys 0m0.220s We can improve this by skipping "ls-files" completely, and just feeding the original pathspecs to the diff commands.

从历史上看,“diff-index”支持的路径规范语言比较弱,但现在情况已经不同了。

由于这里没有提到,还可以考虑“魔术签名”:/来递归地添加项目根目录下的任何匹配项:

git add :/*.{java,pom}

Tx到:https://stackoverflow.com/a/64210713/2586761

添加一个之前没有提到的Windows命令行解决方案:

for /f "delims=" %G in ('dir /b/s *.java') do @git add %G

你可以使用git add [path]/\*.java从子目录中添加java文件, 例如,git为当前目录添加。/\*.java。

从git添加文档:

添加文档目录及其子目录下所有*.txt文件中的内容: $ git添加文档/\*.txt 注意,星号*引用自本例中的shell;这让该命令包含Documentation/ directory子目录中的文件。

如果要添加的一些文件可能还没有被跟踪,Sergio Acosta的答案可能是您的最佳选择。如果你想把自己限制在git已经知道的文件中,你可以把git-ls-files和一个过滤器结合起来:

git ls-files [path] | grep '\.java$' | xargs git add

Git本身并没有提供任何花哨的机制来实现这一点,因为它基本上是一个shell问题:如何获得作为给定命令的参数提供的文件列表。