0

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.

3 Answers3

2

printf is the way to go to format numbers:

printf "There were %03d files\n" "$(ls | wc -l)"
that other guy
  • 116,971
  • 11
  • 170
  • 194
0

You coud use sed.

ls | wc -l | sed 's/^17$/017/'

And this applies to all the two digit numbers.

ls | wc -l | sed '/^[0-9][0-9]$/s/.*/0&/'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Thank you for the help. the second suggestion is close, the files in this dir can range from 5 - 150. so I played with your suggestion and currently: ls | wc -l | sed '/^[0-999]$/s/.*/00&/' this gives me three digit output if the count is 9 or less and 100+ but 2 digits still return as two digits. – Threepwood Feb 07 '15 at 01:50
0

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.

kojiro
  • 74,557
  • 19
  • 143
  • 201