How can I list only non-empty files using ls?
Solution 1
I'd use find dirname -not -empty -ls
, assuming GNU find.
Solution 2
This is a job for find ls is not powerful enough.
find -maxdepth 1 -size +0 -print
-maxdepth 1
- this tells find to search the current dir only, remove to look in all sub dirs or change the number to go down 2, 3 or more levels.
-size +0
this tells find to look for files with size larger than 0
bytes. 0
can be changed to any size you would want.
-print
tells find to print out the full path to the file it finds
Edit:
Late addition: You should probably also add the -type f
switch above. This tells find to only find files. And as noted in comments below, the -print
switch is not really needed.
Solution 3
ls -l | awk '{if ($5 != 0) print $9}'
If you are intent on using ls
, you need a little help from awk
.
Solution 4
find dirname -type f ! -empty
Solution 5
Ls has almost no option to filter files: that's not its job. Filtering files is the job of the shell for simple cases (through globbing) and the job of find for complex cases.
In zsh, you can the L
globbing qualifier to retain only files whose size is >0 (the .
qualifier restricts to regular files):
ls *(.L+0)
Users of other shells must use find. With GNU find (as found mostly on Linux):
find -maxdepth 1 -type f ! -empty -exec ls {} +
A POSIX-compliant way is:
find . -type f -size +0c -exec ls {} + -o -name . -o -prune
If ls
wasn't just an example and you merely intend visual inspection, you could sort by size: ls -S
.
Related videos on Youtube
![Moreno Ambrosin](https://lh3.googleusercontent.com/-PVtdwEmtlFQ/AAAAAAAAAAI/AAAAAAAAAEM/C7D1oWL8w0A/photo.jpg?sz=256)
Moreno Ambrosin
Updated on September 17, 2022Comments
-
Moreno Ambrosin almost 2 years
How can I list (using
ls
) all files that are not empty (size > 0) using linux? -
cYrus almost 14 yearsTo avoid a warning you should place
-maxdepth 1
before-size +0
. Also-print
is the default action, so it's not needed. -
Julian almost 14 years@cYrus - No warnings for me (cygwin)
-
Daenyth almost 14 yearsAnyone care to explain the downvote?
-
Telemachus over 13 yearsImplementations of
find
vary a lot in terms of what valid options are and where they can go. GNUfind
(which is awfully common) will produce a warning if you put-size
before-maxdepth
. -
Pylsa over 13 yearsProbably because the asker asked for
ls
and you usedfind
;) I upped though... It's a proper solution -
user672009 over 7 yearsIf you use "find . -not -empty -ls" it will also include the current directory (ie "." in it's output), to just include the current files use "find . -type f -not -empty -ls"