0

Related to this question.

How do I count the number of files in a directory so huge that ls returns too many characters for the command line to handle?

$ ls 150_sims/combined/ | wc -l
bash: /bin/ls: Argument list too long
Michael
  • 5,775
  • 2
  • 34
  • 53
  • 2
    How many files are in the directory? – Cyrus Aug 31 '19 at 00:07
  • 3
    The error message does not match your command. Have you used `ls 150_sims/combined/` or `ls 150_sims/combined/*`? – Cyrus Aug 31 '19 at 00:08
  • 1
    Related: [What is the best way to count “find” results?](https://stackoverflow.com/q/15663607/4518341) – wjandrea Aug 31 '19 at 00:15
  • find 150_sims/ -type f |wc -l – James Li Aug 31 '19 at 00:15
  • If you're going to parse `ls`, you'll want to use `ls -f`. If you have a lot of entries, the performance difference is noticeable. – William Pursell Aug 31 '19 at 00:15
  • If you read the answer to the link in @wjandrea comment, using `find` with `-printf '.'` will output a single `'.'` character per-file which you can pipe to `wc -c` to get the file count. So each file takes no more than a single-character to represent. (at the command line use `getconf ARG_MAX` to get the character limit, usually `2097152` for Linux) – David C. Rankin Aug 31 '19 at 07:08

2 Answers2

1

Try this:

$ find 150_sims/combined/ -maxdepth 1 -type f | wc -l

If you're sure there are no directories inside your directory, you can reduce the command to just:

$ find 150_sims/combined/ | wc -l
JL. Sanchez
  • 371
  • 1
  • 7
  • What if a filename contains a permitted line break? [See](https://stackoverflow.com/a/15663760/3776858). – Cyrus Aug 31 '19 at 00:18
  • Then use `find 150_sims/combined/ -maxdepth 1 -type f -printf '.' | wc -c` and it will work with whatever file name – Léa Gris Aug 31 '19 at 00:21
0

If there are no newlines in file names, a simple ls -A | wc -l tells you how many files there are in the directory. Please note that if you have an alias for ls, this may trigger a call to stat (Example: ls --color or ls -F need to know the file type, which requires a call to stat), so from the command line, call command ls -A | wc -l or \ls -A | wc -l to avoid an alias.

ls -A 150_sims/combined | wc -l

If you are interested in counting both the files and directories you can try something like this:

\ls -afq 150_sims/combined | wc -l

This includes . and .., so you need subtract 2 from the count:

echo $(\ls -afq 150_sims/combined | wc -l) - 2 | bc
1218985
  • 7,531
  • 2
  • 25
  • 31