Liondancer
Liondancer

Reputation: 16469

Bash command for output of only directories based on regex

I am not too savvy with shell commands. But I was wondering if there was a way to list all ONLY the directories (no files) that contain a certain regex parttern?

For instance:

a/
   /dir1
      /d_332
         file1.txt
   /dir2
      /d_123
         file2.txt
   /dir3
      /dir4
         /dir5
            /d_444
               file3.txt 

The regex I want to use is d_\d+ to find all directories that start with d_ and have a series of numbers. This it Python regex. I am not sure how different it is compared to bash regex

This command would give me an output of:

a/dir1/d_332/
a/dir2/d_123/
a/dir3/dir4/dir5/d_444/

Upvotes: 0

Views: 57

Answers (2)

Wintermute
Wintermute

Reputation: 44023

Use the find utility:

find path -type d -regex '.*/d_[0-9]+'

path would in your case be a; it's the top of the directory tree find is going to search.

This uses two filters:

  1. -type d filters for directories, and
  2. -regex '.*/d_[0-9]+' filters for paths (full paths) that match the regex .*/d_[0-9]+. The regex is applied to the full path as find prints it, not just a part of it; that's why the .* at the beginning is required.

Those entries in the directory tree that match both filters are printed.

There's also a -regextype option that allows you to use a few different flavors of regular expressions, so you may want to take a look at the manpage.

Upvotes: 2

michael501
michael501

Reputation: 1482

try this :

 find . -type d -name 'd*[0-9]*'

Upvotes: 1

Related Questions