LINUX

[ Solved -3 Answers] How can we get files with numeric names using ls command

How can we get files with numeric names using ls command -this is not very optimal, as find searches only filters out desired

In linux command line, how can we 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 we get the list of process ids on the system in linux command prompt?, where we’ve run ls on /proc/.  now trying to exclude everything except the process ID directories.

  • Using ls piped to grep -E (extended grep with additional regexp capabilities) to search for all filenames with only numeric characters:
bash code
ls | grep -E '^[0-9]+$'

  • 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
bash code
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:

bash code
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.

  • If you’re wanting to use ls, you could use:
bash code
  ls *[[:digit:]]*
  • The * splat operator will match any [[:digit:]]. You could also use:
bash code
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.
READ  How to Run Multiple Distros Simultaneously Using Linux Containers

About the author

Wikitechy Editor

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

X