How to grep for a file extension

On UNIX, try:

find . -type f -name \*.zip

You can also use grep to find all files with a specific extension:

find .|grep -e "\.gz$"

The . means the current folder. If you want to specify a folder other than the current folder, just replace the . with the path of the folder. Here is an example: Let's find all files that end with .gz and are in the folder /var/log

  find /var/log/ |grep -e "\.gz$"

The output is something similar to the following:

 ✘ ⚙> find /var/log/ |grep -e "\.gz$"

/var/log//mail.log.1.gz
/var/log//mail.log.0.gz
/var/log//system.log.3.gz
/var/log//system.log.7.gz
/var/log//system.log.6.gz
/var/log//system.log.2.gz
/var/log//system.log.5.gz
/var/log//system.log.1.gz
/var/log//system.log.0.gz
/var/log//system.log.4.gz

The $ sign says that the file extension is ending with gz


Test for the end of the line with $ and escape the second . with a backslash so it only matches a period and not any character.

grep ".*\.zip$"

However ls *.zip is a more natural way to do this if you want to list all the .zip files in the current directory or find . -name "*.zip" for all .zip files in the sub-directories starting from (and including) the current directory.

Tags:

Regex

Bash

Grep