我如何递归地通过位于不同目录的模式(或glob)添加文件?
例如,我想用一个命令添加A/B/C/foo.java和D/E/F/bar.java(以及其他几个java文件):
git add '*.java'
不幸的是,这并没有像预期的那样起作用。
我如何递归地通过位于不同目录的模式(或glob)添加文件?
例如,我想用一个命令添加A/B/C/foo.java和D/E/F/bar.java(以及其他几个java文件):
git add '*.java'
不幸的是,这并没有像预期的那样起作用。
当前回答
如果要添加的一些文件可能还没有被跟踪,Sergio Acosta的答案可能是您的最佳选择。如果你想把自己限制在git已经知道的文件中,你可以把git-ls-files和一个过滤器结合起来:
git ls-files [path] | grep '\.java$' | xargs git add
Git本身并没有提供任何花哨的机制来实现这一点,因为它基本上是一个shell问题:如何获得作为给定命令的参数提供的文件列表。
其他回答
有点偏离主题(不是特别与git相关),但如果你在linux/unix上,一个变通方法可以是:
find . -name '*.java' | xargs git add
如果你期望路径有空格
find . -name '*.java' -print0 | xargs -0 git add
但我知道这不是你想要的。
我在GNUmakefile中使用的一个变体
.PHONY: docs
docs:
@echo docs
bash -c "if pgrep MacDown; then pkill MacDown; fi"
bash -c 'cat $(PWD)/HEADER.md > $(PWD)/README.md'
bash -c 'cat $(PWD)/COMMANDS.md >> $(PWD)/README.md'
bash -c 'cat $(PWD)/FOOTER.md >> $(PWD)/README.md'
bash -c 'pandoc -s README.md -o index.html'
bash -c "if hash open 2>/dev/null; then open README.md; fi || echo failed to open README.md"
#git add --ignore-errors *.md
git ls-files -co --exclude-standard | grep '\.md/$\' | xargs git
添加一个之前没有提到的Windows命令行解决方案:
for /f "delims=" %G in ('dir /b/s *.java') do @git add %G
把行放在~/.gitconfig中
(化名) addt = ! sh - c“git ls-files | grep \ \”。$ 1 * \ " | xargs git add”——
如果你想添加所有修改过的java文件,只需做: Git addt Java
同样地,如果你想添加所有修改过的python文件,可以这样做: Git addt py
正如在“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”支持的路径规范语言比较弱,但现在情况已经不同了。