在bash中仅列出使用ls的目录:检查

该命令列出当前路径中的目录: ls -d */

模式*/究竟做了什么?

我们如何才能在上面的命令中给出绝对路径(例如ls -d /home/alice/Documents )以仅列出该路径中的目录?


*/是一个匹配当前目录中所有子目录的模式( *会匹配所有文件和子目录; /限制它到目录)。 同样,要列出/ home / alice / Documents下的所有子目录,请使用ls -d /home/alice/Documents/*/


四种方法来完成这项工作,每种方法都有不同的输出格式

1.使用echo

例如: echo */echo */*/
这是我得到的:

cs/ draft/ files/ hacks/ masters/ static/  
cs/code/ files/images/ static/images/ static/stylesheets/  

2.仅使用ls

例如: ls -d */
这正是我得到的:

cs/     files/      masters/  
draft/  hacks/      static/  

或作为列表(具有详细信息): ls -dl */

3.使用lsgrep

例如: ls -l | grep "^d" ls -l | grep "^d"这是我得到的:

drwxr-xr-x  24 h  staff     816 Jun  8 10:55 cs  
drwxr-xr-x   6 h  staff     204 Jun  8 10:55 draft  
drwxr-xr-x   9 h  staff     306 Jun  8 10:55 files  
drwxr-xr-x   2 h  staff      68 Jun  9 13:19 hacks  
drwxr-xr-x   6 h  staff     204 Jun  8 10:55 masters  
drwxr-xr-x   4 h  staff     136 Jun  8 10:55 static  

4. Bash脚本(不建议用于文件名包含空格。)

例如: for i in $(ls -d */); do echo ${i%%/}; done for i in $(ls -d */); do echo ${i%%/}; done
这是我得到的:

cs  
draft  
files  
hacks  
masters  
static

如果你喜欢用'/'作为结尾字符,命令将是: for i in $(ls -d */); do echo ${i}; done for i in $(ls -d */); do echo ${i}; done

cs/  
draft/  
files/  
hacks/  
masters/  
static/

我用:

ls -d */ | cut -f1 -d'/'

这会创建一个没有结尾斜杠的单列 - 在脚本中很有用。

我的两分钱。

链接地址: http://www.djcxy.com/p/9291.html

上一篇: Listing only directories using ls in bash: An examination

下一篇: How can I find script's directory with Python?