Android_enthusiast
Android_enthusiast

Reputation: 903

find only files with extension using ls

I need to find only files in directory which have a extension using ls (can't use find).

I tried ls *.*, but if dir doesn't contain any file with extension it returns "No such file or directory".

I dont want that error and want ls to return to cmd prompt if there are files with extension.

I have trying to use grep with ls to achieve the same.

ls|grep "*.*" - doesn't work but ls | grep "\." works.

I have no idea why grep *.* doesn't work. Any help is appreciated!

Thanks!

Upvotes: 0

Views: 6748

Answers (3)

0zkr PM
0zkr PM

Reputation: 863

Try

ls -1 | grep "\."

list only files with extensión and nothing (empty list) if there is no file: like you need.

With Linux grep, you can add -v to get a list files with no extension.

Upvotes: 2

ruakh
ruakh

Reputation: 183321

I think the correct solution is this:

( shopt -s nullglob ; echo *.* )

It's a bit verbose, but it will always work no matter what kind of funky filenames you have. (The problem with piping ls to grep is that typical systems allow really bizarre characters in filenames, including, for example, newlines.)

The shopt -s nullglob part enables ("sets") the nullglob shell optoption, which tells Bash that if no files have names matching *.*, then the *.* should be removed (i.e., should expand into nothing) rather than being left alone.

The parentheses (...) are to set up a subshell, so the nullglob option is only enabled for this small part of the script.

Upvotes: 2

Vaughn Cato
Vaughn Cato

Reputation: 64308

It's important to understand the difference between a shell pattern and a regular expression. Shell patterns are a bit simpler, but less flexible. grep matches using a regular expression. A shell pattern like

*.*

would be done with a regular expression as

.*\..*

but the regular expressions in grep are not anchored, which means it searches for a match anywhere on the line, making the two .* parts unnecessary.

Upvotes: 1

Related Questions