Listing only directories using ls in bash: An exam

2019-01-05 06:22发布

This command lists directories in the current path: ls -d */

What exactly does the pattern */ do?

And how can we give the absolute path in the above command (e.g. ls -d /home/alice/Documents) for listing only directories in that path?

25条回答
Summer. ? 凉城
2楼-- · 2019-01-05 07:20

*/ is a filename matching pattern that matches directories in the current directory.

To list directories only, I like this function:

# long list only directories
llod () { 
  ls -l --color=always "$@" | grep --color=never '^d'
}

Put it in your .bashrc.

Usage examples:

llod       # long listing of all directories in current directory
llod -tr   # same but in chronological order oldest first
llod -d a* # limit to directories beginning with letter 'a'
llod -d .* # limit to hidden directories

NOTE: it will break if you use the -i option. Here is a fix for that:

# long list only directories
llod () { 
  ls -l --color=always "$@" | egrep --color=never '^d|^[[:digit:]]+ d'
}
查看更多
仙女界的扛把子
3楼-- · 2019-01-05 07:20

To answer the original question, */ has nothing to do with ls per se; it is done by the shell/Bash, in a process known as globbing.

This is why echo */ and ls -d */ output the same elements. (The -d flag makes ls output the directory names and not contents of the directories.)

查看更多
Bombasti
4楼-- · 2019-01-05 07:23

*/ is a pattern that matches all of the subdirectories in the current directory (* would match all files and subdirectories; the / restricts it to directories). Similarly, to list all subdirectories under /home/alice/Documents, use ls -d /home/alice/Documents/*/

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-05 07:23

For listing only directories:

ls -l | grep ^d

for listing only files:

ls -l | grep -v ^d 

or also you can do as: ls -ld */

查看更多
Root(大扎)
6楼-- · 2019-01-05 07:25

For all folders without subfolders:

find /home/alice/Documents -maxdepth 1 -type d

For all folders with subfolders:

find /home/alice/Documents -type d
查看更多
迷人小祖宗
7楼-- · 2019-01-05 07:25

Using Perl:

ls | perl -nle 'print if -d;'
查看更多
登录 后发表回答