How to: Linux or UNIX List just directories or directory names

Q. How do I list just directory names under Linux?
A. Under Linux or UNIX use ls command to list files and directories. However ls does not have an option to list only directories. You can use combination of ls and grep to list directory names only.

Display or list all directories

Type the following command:
$ ls -l | egrep `^d'

Display or list only files

Type the following command:
$ ls -l | egrep -v `^d'
grep command used to searches input. It will filter out directories name by matching first character d. To reverse effect (just to display files) you need to pass -v option. It invert the sense of matching, to select non-matching lines.

Task: Create aliases to save time

You can create two aliases as follows to list only directories and files.
alias lf="ls -l | egrep -v '^d'"
alias ldir="ls -l | egrep '^d'"

Put above two aliases in your bash shell startup file:
$ cd
$ vi .bash_profile

Append two lines:
alias lf="ls -l | egrep -v '^d'"
alias ldir="ls -l | egrep '^d'"

Save and close the file.
Now just type lf - to list files and ldir - to list directories only:
$ cd /etc
$ lf

Output:
-rw-r--r--   1 root root      2149 2006-09-04 23:25 adduser.conf
-rw-r--r--   1 root root        44 2006-09-29 05:11 adjtime
-rw-r--r--   1 root root       197 2006-09-04 23:48 aliases
-rw-------   1 root root       144 2002-01-18 13:43 at.deny
-rw-r--r--   1 root root       162 2006-09-22 23:24 aumixrc
-rw-r--r--   1 root root        28 2006-09-22 23:24 aumixrc1
....
..
....
List directory names only:
$ cd /etc
$ ldir

No comments:

Post a Comment