I am currently not on a Linux machine. Would the following command produce my wanted result?

ls | grep ".pdf" | wc

  • not necessarily ending with .pdf....this will count all files containing .pdf, like image.pdf0001.jpg... – mazs May 21 '16 at 14:37
  • and ls will list folders as well, if any subfolder contains the .pdf characters, those will be counted too. – mazs May 21 '16 at 14:51
  • and lastly, you should specify what exactly is your wanted result, because the command you've given might produce the wanted result. – mazs May 21 '16 at 14:53
  • @roaima: the OP asked to count "the *.pdf files", not "the PDF files", so the answers do address the question. :-) – L. Levrel May 21 '16 at 17:49

No, ".pdf" macthes way too much, e.g foo.pdfa and bpdf.

Furthermore, even if you don't have files wrongly matching, wc without options outputs the number of lines, words and bytes in the input, so you would get two numbers more than you're interested in. If you want grep in the mix, you could do ls | grep -E "\.pdf$" | wc -l, but unless you have a lot of pdf-files in that directory grep isn't needed, you can get by with ls *.pdf | wc -l.

Added later, when I got to think this through:

Also, grep can do the counting so if grep is in the mix, just add the -c option to grep instead of piping the output to wc -l, so ls | grep -cE "\.pdf$" or if you want to avoid counting directories named <something.pdf>: ls -l | grep -cE "^-.*\.pdf$".

  • this will also count folders matching the pattern – mazs May 21 '16 at 14:42
  • I've added a solution to the answer that addresses that. – Henrik supports the community May 21 '16 at 17:12

Your shell should be able to do the filtering:

ls *.pdf | wc -l

or you have to make sure you match the end of filenames:

ls | grep "*\.pdf$" | wc -l

(notice the dollar sign).

Note: both of these will also match directories ending in ".pdf", if any.

Note 2: ls should behave as if you gave it option -1 as soon as you pipe its output. Otherwise, add this switch.

  • add ls -1 or you will count lines but not files – MolbOrg May 21 '16 at 13:32
  • @MolbOrg: see the 2nd note I've just added: ls automatically switches to "one-column mode" when you pipe its output. – L. Levrel May 21 '16 at 13:36
  • Yes, true. didn't used that. nice to know now. tnx. – MolbOrg May 21 '16 at 15:10

You should use

ls | grep ".pdf" | wc -l

The -l parameter will count only the number of resulted lines, while without the -l you would get other counts as well, like newline, word, and byte count. Note that this will count filenames (and folders as well) which contain the ".pdf" chain of characters.

To count only files ending with .pdf, you'd better use find :

find . -type f -name "*.pdf" | wc -l

Not the answer you're looking for? Browse other questions tagged or ask your own question.