How to Find All Files with a Specific File Extension in Linux

How can we find all .md files in a directory? Well, there are multiple ways to do this.

The first way is to use ls.

Using ls

We can use ls to list all .md files in the current directory

ls *.md

Using find

We can use find to list all .md files in the current directory as well as all subdirectories.

find . -name "*.md"

Using find and grep

grep -i \.md$

-i makes grep case insensitive so that it matches .md as well as .MD.

\. escapes the period and searches for a literal period. Without the backslash \, the period . matches any non space or newline character.

md searches for the text md.

$ is an end of line character. It ensures that the md is the last text in that line.

Let’s try it without the $.

grep -i \.md

This command would match all kinds of file extensions:

  • .md
  • .mddddd
  • .mdoweijfoiewf

So the $ is kind of important.

We can also add -r to recursively search every subdirectory as well as the current directory.

grep -ir \.md$

However, since grep searches file contents, using only grep will return file contents that have .md in them.

As a result, we can just use find and pipe the output to grep to only search filenames.

find . | grep \.md$

The period . will only search in the current directory. Feel free to change this to whatever directory path you want to search through.

The reason why we would ever use this method over just find is if we want to leverage the power of regular expressions in our grep command.