Thursday, March 10, 2011

bfsize - print file size in bytes (and just that)

I need to know the size in bytes of a file a few times a day. With du, I need to do this:

$ du -b /usr/bin/du | cut -f1
97536

With ls, I need to do this:

$ ls -l /bin/ls | cut -d' ' -f5
108008

So I've just coded a small program to do that without needing to cut the output. It's called bfsize and it is available in my repository named bftools on github.

Example:

$ bfsize /usr/local/bin/bfsize
7371

EDIT: just for fun, I've been searching for other ways to do it, here are some:

$ perl -e 'printf "%d\n",(stat(shift))[7];' /usr/bin/perl
6928

$ stat -c %s /usr/bin/stat
50000

$ wc -c < /usr/bin/wc
36912

$ find /usr/bin/find -printf "%s\n"
226256

3 comments:

  1. For text files:
    wc filename | cut -d' ' -f5

    ReplyDelete
  2. What about making a shell script that does that instead of a full C-binary?

    #!/bin/bash
    wc -c < $1

    ReplyDelete
    Replies
    1. Isn't calling the "wc" program (or "stat" or "ls") also calling a "full C-binary" program? What's the difference (problem) in calling an alternate program?

      I don't like the "wc -c" approach at all. It's ok to use it from the command line, or as an occasional thing, but I'd never use it from within a shell script that would processs lots of files. "wc" will read the entire file to obtain the file size which could take lots of time, especially if you are processing many files or if you are processing files that are very large.

      Delete