Wednesday, July 27, 2022

[SOLVED] How to grep for a file extension

Issue

I am currently trying to a make a script that would grep input to see if something is of a certain file type (zip for instance), although the text before the file type could be anything, so for instance

something.zip
this.zip
that.zip

would all fall under the category. I am trying to grep for these using a wildcard, and so far I have tried this

grep ".*.zip"

But whenever I do that, it will find the .zip files just fine, but it will still display output if there are additional characters after the .zip so for instance .zippppppp or .zipdsjdskjc would still be picked up by grep. Having said that, what should I do to prevent grep from displaying matches that have additional characters after the .zip?


Solution

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.



Answered By - Chris Seymour
Answer Checked By - Gilberto Lyons (WPSolving Admin)