Home > OS >  How can I list the files in a directory that have zero size/length in the Linux terminal?
How can I list the files in a directory that have zero size/length in the Linux terminal?

Time:11-28

I am new to using the Linux terminal, so I'm just starting to learn about the commands I can use. I have figured out how to list the files in a directory using the Linux terminal, and how to list them according to file size. I was wondering if there's a way to list only the files of a specific file size. Right now, I'm trying to list files with zero size, like those that you might create using the touch command. I looked through the flags I could use when I use ls, but I couldn't find exactly what I was looking for. Here's what I have right now:

ls -lsh /mydirectory

The "mydirectory" part is just a placeholder. Is there anything I can add that will only list files that have zero size?

CodePudding user response:

There's a few ways you can go about this; if you want to stick with ls -l you could use e.g. awk in a pipeline to do the filtering.

ls -lsh /mydirectory | awk '$5 == 0'

Here, $5 is the fifth field in ls's output, the size.

Another approach would be to use a different tool, find.

find /mydirectory -maxdepth 1 -size 0 -ls

This will also list hidden files, analogous to an ls -la. The -maxdepth 1 is there so it doesn't traverse the directory tree if you have nested directories.

CodePudding user response:

A simple script can do this.

    for file_name in *
    do
      if [[ !( -s $file_name ) ]]
      then
          echo $file_name
      fi
    done

explanation:

for is a loop. * gives list of all files in a current directory. -s file_name becomes true if the file has size greater than 0.

! to negate that

  • Related