How can I get files with numeric names using ls command?

In linux commandline, how can I list down only numeric(only names with 0 to 9) file names in the current directory?

This is a follow-on question to How can I get the list of process ids on the system in linux command prompt?, where I've run ls on /proc/. I'm now trying to exclude everything except the process ID directories.


Solution 1:

Using ls piped to grep -E (extended grep with additional regexp capabilities) to search for all filenames with only numeric characters:

ls | grep -E '^[0-9]+$'

Solution 2:

Despite of your question title, I want to present you a solution with find. It has a regex option (-regex), so [0-9]* will match file names consisting solely out of digits.

To find only files (-type f) recursively below the current directory (.) use

find . -type f -regex ".*/[0-9]*"

The .*/ in the regex is necessary, because regex "is a match on the whole path, not a search." (man find). So if you want to find only files in the current dir, use \./ instead:

find . -type f -regex "\./[0-9]*"

However, this is not very optimal, as find searches recursively also in this case and only filters out the desired results afterwards.

Solution 3:

If you're wanting to use ls, you could use:

ls *[[:digit:]]*

The * splat operator will match any [[:digit:]]. You could also use:

ls *[0-9]*

Which also matches file or directory with a digit 0-9.

If you have subdirectories that match the glob pattern, you can use the -d switch to make ls not recurse into them.