Nate
Nate

Reputation: 778

How do I exclude files from git ls-files?

How do I list everything except markdown files? I have tried to run ls-files with the --exclude flag, but the excluded files are still shown in the output.

My git version is 2.6.4 (Apple Git-63)

$ git ls-files
ChromeExt/read-coffee
Node/README.md
Node/web-scraping
README.md

$ git ls-files --exclude *.md
ChromeExt/read-coffee
Node/README.md
Node/web-scraping
README.md

Upvotes: 44

Views: 20949

Answers (4)

Clay Risser
Clay Risser

Reputation: 3570

How about using a grep reverse match -v?

git ls-files | grep -v -E "\.md$"

Upvotes: 2

geirha
geirha

Reputation: 6181

Git has its own way to extend glob patterns, and that includes a way to exclude files that match one pattern but not another. For example, the following will list all paths not ending in .md:

git ls-files -- . ':!:*.md'

It's important to quote the pattern, because you want git to parse it, not the shell.

And to match all files ending with .js, except the ones ending with .min.js:

git ls-files -- '*.js' ':!:*.min.js'

You can also use this with other commands, such as git grep:

git grep -w funcname -- '*.js' ':!:*.min.js'

This syntax is explained under pathspec in gitglossary (or git help glossary or man gitglossary)

Upvotes: 69

Batiaev
Batiaev

Reputation: 1171

You do not need to use the --exclude parameter because this key is only used for skipping untracked files:

$ man git-ls-files

-x <pattern>, --exclude=<pattern>
       Skip untracked files matching pattern. Note that pattern is a shell wildcard pattern. See EXCLUDE PATTERNS below for more information.

You should just use a mask for required files

In your case (excluding *.md files):

$ git ls-files
example1.txt
example2.pdf
readme.md

$ git ls-files *[^.md]
example1.txt
example2.pdf

Upvotes: 8

VonC
VonC

Reputation: 1323593

That was already discussed in 2010:

There is no indication in the man page that -x doesn't apply to -c.

Hence the addition:

Since b5227d8, -x/--exclude does not apply to cached files.
This is easy to miss unless you read the discussion in the EXCLUDE PATTERNS section. Clarify that the option applies to untracked files and direct the reader to EXCLUDE PATTERNS.

The git ls-files man page does mentions:

-x <pattern>
--exclude=<pattern>

Skip untracked files matching pattern

If your Readme.md is tracked, the exclude pattern won't apply.

Upvotes: 12

Related Questions