ag.lis
ag.lis

Reputation: 31

How to display directories that begins with small or capital letter in Linux?

I want to display all directory names in directory /opt/BMC/patrol/ that begin with Patrol* or patrol*. Command

ls /opt/BMC/patrol/ | grep -i '^Patrol*'

produces

Patrol3
Patrol3.16
PatrolAgent_3181.sh
patrol_cfg.sh

It is correct but there are directories and files, instead of just directories.

Command ls -d /opt/BMC/patrol/*/ | grep -i '^Patrol*' produces nothing...

Command ls -d /opt/BMC/patrol/*/ | grep -i 'Patrol*' produces

/opt/BMC/patrol/BMCINSTALL/
/opt/BMC/patrol/bmc_products/
/opt/BMC/patrol/cert_gg/
/opt/BMC/patrol/common/
/opt/BMC/patrol/Install/
/opt/BMC/patrol/itools/
/opt/BMC/patrol/Patrol3/
/opt/BMC/patrol/Patrol3.16/
/opt/BMC/patrol/perform/
/opt/BMC/patrol/rtserver/
/opt/BMC/patrol/temp2/
/opt/BMC/patrol/test/
/opt/BMC/patrol/testftp/
/opt/BMC/patrol/Uninstall/

Does it search recursively? What is a command to find only directory names that begins with capital or small letters?

Upvotes: 1

Views: 916

Answers (1)

cxw
cxw

Reputation: 17051

Try find:

find /opt/BMC/patrol -type d -iname 'patrol*'

-type d matches directories, and -iname is a case-insensitive match. The 'patrol*' has to be quoted '' because otherwise the shell will expand the * before find gets a chance.

find does search recursively by default (see Edit 2, below).

Edit ls is not optimized for this use case. ls -d prevents descending into directories, which is why you don't get any matches. As far as grep goes, ^ matches at the beginning of the line, not at the leading / before a directory's name. So grep -i '\/patrol' would be a way to find names beginning with Patrol or patrol, but you would still have to filter down to directories. find is designed to handle all these things.

Edit 2 For non-recursive, use -maxdepth:

find /opt/BMC/patrol -maxdepth 1 -type d -iname 'patrol*'

I made a test directory with the following contents, based on your question:

opt/BMC/patrol/
opt/BMC/patrol/BMCINSTALL/
opt/BMC/patrol/bmc_products/
opt/BMC/patrol/cert_gg/
opt/BMC/patrol/common/
opt/BMC/patrol/common/patrol.d/
opt/BMC/patrol/Install/
opt/BMC/patrol/itools/
opt/BMC/patrol/Patrol3/
opt/BMC/patrol/Patrol3.16/
opt/BMC/patrol/PatrolAgent_3181.sh
opt/BMC/patrol/patrol_cfg.sh
opt/BMC/patrol/perform/
opt/BMC/patrol/rtserver/
opt/BMC/patrol/temp2/
opt/BMC/patrol/test/
opt/BMC/patrol/testftp/
opt/BMC/patrol/Uninstall/

When I run the first command (without -maxdepth), I get:

opt/BMC/patrol
opt/BMC/patrol/common/patrol.d
opt/BMC/patrol/Patrol3
opt/BMC/patrol/Patrol3.16

When I run the second command (with -maxdepth), I get:

opt/BMC/patrol
opt/BMC/patrol/Patrol3
opt/BMC/patrol/Patrol3.16

and common/patrol.d is not present in the results.

Upvotes: 2

Related Questions