Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: How to list all files/directories, using only ls

This is a question given at university.

The question is: List all files/directories inside testfiles folder, that have no extension.
The right answer given is this:

ls testfiles | grep -v "\."

Now, just to understand how ls regex works, could someone please explain to me how this would be by using only ls? Moreover, I would appreciate any example that also uses the dollar sign $, to specifically state that the name ends with .[a-z].

Any help, really appreciated.

One more thing! Another answer to this question is using:

ls testfiles | grep "^[^.]*$"

How is that read? I read ^[^.]*$ like this:

^      -> does not contain
[^.]   -> starts with a dot
*      -> repeated zero or more times
$      -> till the end

I would like someone to correct me on this... Thanks!

like image 900
m.spyratos Avatar asked Jan 29 '26 07:01

m.spyratos


2 Answers

Unix utilities were meant to be used as filters, so the answer given makes sense since it best approximates a real-world application.

You do understand, though, that grep "\." matches everything with a "period" (hence, extension), and grep -v "\." matches everything else (i.e., the complement).

It is hard to make the command any more precise than what it is already, since who can say what's intended to be an extension, and what's not?


Part 2: ls testfiles | grep "^[^.]*$"

A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list; if the first character of the list is the caret ^ then it matches any character not in the list. For example, the regular expression [0123456789] matches any single digit.

http://unixhelp.ed.ac.uk/CGI/man-cgi?grep

So ^[^.]*$ actually means:

Anything that begins and ends with a string of characters, each of which is not a period.

The first caret is not a negation, it means begins with. The second caret is the "not" signifier.

like image 94
ktm5124 Avatar answered Jan 30 '26 23:01

ktm5124


Correction:

^      -> pattern starts at the beginning of the string
[^.]   -> matches something that is not a dot
*      -> repeated zero or more times
$      -> and must continue to match (only non-dot items) until the end

Thus, it must have only non-dot things from the beginning to the end.

like image 23
Charles Duffy Avatar answered Jan 30 '26 23:01

Charles Duffy