该命令列出当前路径下的目录:
ls -d */
模式*/到底做什么?
我们如何在上面的命令中给出绝对路径(例如ls -d /home/alice/Documents),只列出该路径下的目录?
该命令列出当前路径下的目录:
ls -d */
模式*/到底做什么?
我们如何在上面的命令中给出绝对路径(例如ls -d /home/alice/Documents),只列出该路径下的目录?
当前回答
树命令在这里也非常有用。默认情况下,它将完整地显示所有文件和目录,并使用一些ASCII字符显示目录树。
$ tree
.
├── config.dat
├── data
│ ├── data1.bin
│ ├── data2.inf
│ └── sql
| │ └── data3.sql
├── images
│ ├── background.jpg
│ ├── icon.gif
│ └── logo.jpg
├── program.exe
└── readme.txt
但是如果我们想要只获取目录,而不使用ASCII树,并且使用当前目录的完整路径,你可以这样做:
$ tree -dfi
.
./data
./data/sql
./images
论点是:
-d List directories only.
-f Prints the full path prefix for each file.
-i Makes tree not print the indentation lines, useful when used in conjunction with the -f option.
如果你想要绝对路径,你可以从指定当前目录的完整路径开始:
$ tree -dfi "$(pwd)"
/home/alice/Documents
/home/alice/Documents/data
/home/alice/Documents/data/sql
/home/alice/Documents/images
为了限制子目录的数量,你可以用-L level来设置子目录的最大级别,例如:
$ tree -dfi -L 1 "$(pwd)"
/home/alice/Documents
/home/alice/Documents/data
/home/alice/Documents/images
更多的争论可以看到与人树。
其他回答
我使用:
ls -d */ | cut -f1 -d'/'
这将创建一个没有结尾斜杠的单列——在脚本中很有用。
供您参考,如果您想以多行打印所有文件,您可以执行ls -1,这将以单独的行打印每个文件。 file1 file2 file3
有四种方法可以做到这一点,每种方法都有不同的输出格式
1. 使用回声
例如: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.使用ls和grep
示例: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脚本(不推荐用于包含空格的文件名)
例如:$(ls -d */)中的i;执行echo ${i%%/};完成 以下是我得到的:
cs
draft
files
hacks
masters
static
如果你想用'/'作为结尾字符,命令将是:for i in $(ls -d */);执行echo ${i};完成
cs/
draft/
files/
hacks/
masters/
static/
如果你想知道为什么'ls -d */'的输出会给你两个斜杠,比如:
[prompt]$ ls -d */
app// cgi-bin// lib// pub//
这可能是因为您的shell或会话配置文件将ls命令别名为包含-F标志的ls版本。该标志将一个字符附加到每个输出名称(这不是普通文件),表明它是什么类型的文件。因此,一个斜杠来自匹配模式'*/',另一个斜杠是附加的类型指示符。
要解决这个问题,当然可以为ls定义一个不同的别名。然而,为了暂时不调用别名,你可以在命令前加上反斜杠:
\ls -d */
树命令在这里也非常有用。默认情况下,它将完整地显示所有文件和目录,并使用一些ASCII字符显示目录树。
$ tree
.
├── config.dat
├── data
│ ├── data1.bin
│ ├── data2.inf
│ └── sql
| │ └── data3.sql
├── images
│ ├── background.jpg
│ ├── icon.gif
│ └── logo.jpg
├── program.exe
└── readme.txt
但是如果我们想要只获取目录,而不使用ASCII树,并且使用当前目录的完整路径,你可以这样做:
$ tree -dfi
.
./data
./data/sql
./images
论点是:
-d List directories only.
-f Prints the full path prefix for each file.
-i Makes tree not print the indentation lines, useful when used in conjunction with the -f option.
如果你想要绝对路径,你可以从指定当前目录的完整路径开始:
$ tree -dfi "$(pwd)"
/home/alice/Documents
/home/alice/Documents/data
/home/alice/Documents/data/sql
/home/alice/Documents/images
为了限制子目录的数量,你可以用-L level来设置子目录的最大级别,例如:
$ tree -dfi -L 1 "$(pwd)"
/home/alice/Documents
/home/alice/Documents/data
/home/alice/Documents/images
更多的争论可以看到与人树。