7

Is there any way to prevent find and ls -l from listing . and .. in their results? I never care about seeing this result in the output, and it prevents me from effectively piping their output to wc -l to count things accurately.

In case it matters, I am working in zsh.

1
  • You must have ls aliased to ls -a or something similar; ls does not include . or .. by default.
    – chepner
    Oct 17, 2013 at 16:52

3 Answers 3

9

For ls, use -A instead of -a.

from man ls:

   -A, --almost-all
          do not list implied . and ..
4

With zsh:

count() echo $#
count *        # non-hidden files (all types)
count *(D)     # files (all types)
count **/*(D)  # files recursively (all types)
count **/*(D/)  # directories only (recursively)

(zsh globs never include . nor .. even when dotglob is enabled (like with the (D) globbing qualifier)).

To avoid an error message when there is no file, add the N globbing qualifier:

count *(ND)

That causes the glob to expand to nothing (no argument, not an empty argument) if there's no match.

Note that since the newline character is as valid a character as any in a file name, piping the output of ls or find to wc -l is not correct.

POSIXly, you could count the / characters instead of the newline ones:

find . ! -name . -prune -print | grep -c /

Or recursively, using this trick:

find .//. ! -name . -prune -print | grep -c //
2
  • This is great. One thing I noticed though is that if a folder has 0 files count folder outputs no matches found. Is there any way to make it return 0?
    – Josh
    Oct 8, 2013 at 18:13
  • 1
    @Josh, yes, use the N globbing qualifier (nullglob) Oct 8, 2013 at 19:28
3

To get find to exclude the dot directories you can use this:

$ find . ! -path . -type d

Example

$ find . ! -path . -type d | head -5
./.vim_SO
./.vim_SO/bundle
./.vim_SO/bundle/vim-fugitive
./.vim_SO/bundle/vim-fugitive/plugin
./.vim_SO/bundle/vim-fugitive/doc
...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .