Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for files in a git repository by extensions

I have a string like this *.{jpg,png} for example, but the string could also be just *.scss - in fact it is an editorconfig.

Then I want to search for every file of this extension which is tracked by my git repository.

I've tried several methods but didn't find any sufficient solution.

The closest one I've got is: git ls-tree -r master --name-only | grep -E ".*\.jpg"

But this is only working for single file extensions not for something like this git ls-tree -r master --name-only | grep -E ".*\.{jpg,png}".

Anyone could help me?

like image 896
mstruebing Avatar asked Jan 12 '17 11:01

mstruebing


People also ask

How do I find files in a git repository?

While browsing your Git repository, start typing in the path control box to search for the file or folder you are looking for. The interface lists the results starting from your current folder followed by matching items from across the repo.

What is ls command in git?

git directory with the command ls -a . The ls command lists the current directory contents and by default will not show hidden files. If you pass it the -a flag, it will display hidden files. You can navigate into the . git directory like any other normal directory.

What files can be searched using git grep '?

Git ships with a command called grep that allows you to easily search through any committed tree, the working directory, or even the index for a string or regular expression. For the examples that follow, we'll search through the source code for Git itself.


1 Answers

Try this:

git ls-tree -r master --name-only | grep -E '.*\.(jpg|png)'

The expression you tried to pass via -E option is interpreted as any characters (.*), the dot (\.), and the string {jpg,png}. I guess you are confusing the Bash brace expansion with the alternation (|) in a regular expression group (the parenthesis).

Consider using the end-of-line anchor: '.*\.(jpg|png)$'.

Without grep

As @0andriy pointed out you can pass patterns to git ls-files as follows:

git ls-files '*.jpg' '*.png'

Note, you should escape the arguments in order to prevent the filename expansion (globbing). In particular, the asterisk (*) character

matches any number of repeats of the character string or RE preceding it, including zero instances.

But this obviously will work only for the simple git patterns. For a slightly more complicated case such as "extension matching N characters from a given set" you will need a regular expression (and grep, for example).

like image 154
Ruslan Osmanov Avatar answered Sep 18 '22 12:09

Ruslan Osmanov