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

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

git add '*.java'

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


当前回答

我只想添加基于git状态的特定字符串的文件:

Git 状态 |格雷普字符串 |xargs git add

然后能够git commit -m 'commit MSG来提交所有更改过的文件,文件标题中带有“string”

其他回答

有点偏离主题(不是特别与git相关),但如果你在linux/unix上,一个变通方法可以是:

find . -name '*.java' | xargs git add

如果你期望路径有空格

find . -name '*.java' -print0 | xargs -0 git add

但我知道这不是你想要的。

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

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

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

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

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

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

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

正如在“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