Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively add files by pattern

You can use git add [path]/\*.java to add java files from subdirectories,
e.g. git add ./\*.java for current directory.

From git add documentation:

Adds content from all *.txt files under Documentation directory and its subdirectories:

$ git add Documentation/\*.txt

Note that the asterisk * is quoted from the shell in this example; this lets the command include the files from subdirectories of Documentation/ directory.


Sergio Acosta's answer is probably your best bet if some of the files to be added may not already be tracked. If you want to limit yourself to files git already knows about, you could combine git-ls-files with a filter:

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

Git doesn't provide any fancy mechanisms for doing this itself, as it's basically a shell problem: how do you get a list of files to provide as arguments to a given command.


With zsh you can run:

git add "**/*.java"

and all your *.java files will be added recursively.


A bit off topic (not specifically git related) but if you're on linux/unix a workaround could be:

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

And if you expect paths with spaces:

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

But I know that is not exactly what you asked.


Sergey's answer (don't credit me) is working:

You can use git add [path]/\*.java

with a recent git:

$git version
git version 1.7.3.4

Files for the test:

$find -name .git -prune -o -type f -print | sort
./dirA/dirA-1/dirA-1-1/file1.txt
./dirA/dirA-1/dirA-1-2/file2.html
./dirA/dirA-1/dirA-1-2/file3.txt
./dirA/dirA-1/file4.txt
./dirB/dirB-1/dirB-1-1/file5.html
./dirB/dirB-1/dirB-1-1/file6.txt
./file7.txt

Git status:

$git status -s
?? dirA/
?? dirB/
?? file7.txt

Adding *.txt:

$git add \*.txt

Updated status:

$git status -s
A  dirA/dirA-1/dirA-1-1/file1.txt
A  dirA/dirA-1/dirA-1-2/file3.txt
A  dirA/dirA-1/file4.txt
A  dirB/dirB-1/dirB-1-1/file6.txt
A  file7.txt
?? dirA/dirA-1/dirA-1-2/file2.html
?? dirB/dirB-1/dirB-1-1/file5.html

If you are already tracking your files and have made changes to them and now you want to add them selectively based on a pattern, you can use the --modified flag

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

For example, if you only want to add the CSS changes to this commit, you can do

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

See man git-ls-files for more flags