Search code examples
bashlswc

Bash: displaying wc with three digit output?


conducting a word count of a directory.

ls | wc -l

if output is "17", I would like the output to display as "017".

I have played with | printf with little luck. Any suggestions would be appreciated.


Solution

  • ls | wc -l will tell you how many lines it encountered parsing the output of ls, which may not be the same as the number of (non-dot) filenames in the directory. What if a filename has a newline? One reliable way to get the number of files in a directory is

    x=(*)
    printf '%03d\n' "${#x[@]}"
    

    But that will only work with a shell that supports arrays. If you want a POSIX compatible approach, use a shell function:

    countargs() { printf '%03d\n' $#; }
    countargs *
    

    This works because when a glob expands the shell maintains the words in each member of the glob expansion, regardless of the characters in the filename. But when you pipe a filename the command on the other side of the pipe can't tell it's anything other than a normal string, so it can't do any special handling.