3

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

ls | grep ".pdf" | wc

KOB
  • 253
  • not necessarily ending with .pdf....this will count all files containing .pdf, like image.pdf0001.jpg... – magor 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. – magor 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. – magor 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

3 Answers3

3

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
magor
  • 3,752
  • 2
  • 13
  • 28
3

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$".

2

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.

L. Levrel
  • 1,503