Let's say I'd like to know how many .png images I have in a folder. In shell I'd run:

ls -1 | grep .png | wc -l

Is there a way to achieve this in emacs (preferably not just reading in from a shell output)?


2 Answers 2

(length (directory-files "~/Pictures" nil "\\.png\\'"))

See C-hf directory-files

  • Thanks. If I wanted to search for both .png and .jpeg, how would the regex look like? I tried [(.png)|(.jpeg)], but it matches other things too.
    – Daniel
    May 30, 2016 at 9:56
  • I'm afraid that wouldn't do what you wanted in any regular expression syntax I've ever seen. As per Ehvince's comment, you should definitely read some documentation. "\\.\\(png\\|jpeg\\)\\'" will do the trick in Emacs.
    – phils
    May 30, 2016 at 10:53
  • Thanks. I'll go through the documentation. What I'd tried came from playing with the build-in re-builder
    – Daniel
    May 30, 2016 at 10:56
  • FYI you could also use the rx regexp compiler like so: (rx "." (or "png" "jpeg") string-end)
    – phils
    May 30, 2016 at 10:59

In dired (in directory in which you want to count .png files) run M-x eshell-command:

(length (directory-files "" nil "\\.png\\'"))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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