在Linux中仅列出目录
1. 概述
在本教程中,我们将讨论如何仅列出 Linux 中给定路径的目录。有几种方法可以在 Linux 中仅列出目录,我们将在这里介绍其中的一些。
2. 使用ls命令
ls命令是列出目录内容的最常用命令之一。要仅列出目录,我们可以将此命令与 ’ -d ’ 选项一起使用,该选项仅列出当前路径中的目录,而不列出其内容或子目录:
$ ls -d */
arch/ Documentation/ include/ lib/ scripts/ usr/
block/ drivers/ init/ mm/ security/ virt/
certs/ firmware/ ipc/ net/ sound/
crypto/ fs/ kernel/ samples/ tools/
3. 使用dir命令
dir 命令列出目录内容。当我们将此命令与’ -d ‘选项一起使用时,它只会显示有关当前路径中目录的详细信息:
$ dir -d */
drwxr-xr-x 33 HARDIK users 4096 Feb 12 2018 arch/
drwxr-xr-x 3 HARDIK users 4096 Feb 12 2018 block/
drwxr-xr-x 2 HARDIK users 200 Feb 12 2018 certs/
drwxr-xr-x 4 HARDIK users 4096 Feb 12 2018 crypto/
drwxr-xr-x 122 HARDIK users 8192 Feb 12 2018 Documentation/
... ... ... ... ... ... ...
4. 使用find命令
find 命令从目录层次结构中的给定起点开始搜索文件。我们可以将表达式传递给此命令以缩小搜索条件。例如,要列出文件类型目录,我们可以使用带有目录选项“ d ”的“ type ”。此外,为了避免列出子目录的所有内容,我们可以借助“ maxdepth ”来限制搜索级别:
$ find . -maxdepth 1 -type d
.
./Documentation
./arch
./block
./certs
./crypto
...
5. 使用tree命令
tree 命令以深度缩进的树状格式列出目录的内容。我们可以使用此命令在选项 ’ d ‘的帮助下仅显示目录。但是,这也可能列出所有子目录及其内容。所以我们可以使用限制目录树最大显示深度的级别选项( L ):
$ tree -d -L 1
.
├── arch
├── block
├── certs
├── crypto
├── Documentation
...
6. 使用echo命令
正如我们所知,echo 命令将字符串显示回我们传递给它的标准输出。我们还可以使用此命令显示目录的内容。如果我们尝试“ echo */ ”命令,它将显示当前目录的所有内容。此外,要仅列出目录,我们可以像这样使用它:
$ echo */
arch/ block/ certs/ crypto/ Documentation/ drivers/ firmware/
fs/ include/ init/ ipc/ kernel/ lib/ mm/
net/ samples/ scripts/ security/ sound/ tools/ usr/
7. 将grep与其他命令一起使用
当我们使用ls命令 ( ls -l ) 或dir命令的长列表选项列出目录的内容时,我们可以在第一列中看到常规文件显示为“ - ”,目录显示为“ d ”:
$ ls -l
total 708
drwxr-xr-x 33 HARDIK users 4096 Feb 12 2018 arch
drwxr-xr-x 3 HARDIK users 4096 Feb 12 2018 block
drwxr-xr-x 2 HARDIK users 200 Feb 12 2018 certs
-rw-r--r-- 1 HARDIK users 18693 Feb 12 2018 COPYING
-rw-r--r-- 1 HARDIK users 98556 Feb 12 2018 CREDITS
... ... ... ... ... ... ...
所以从这个输出中,我们可以在grep 工具的帮助下过滤目录。Grep 只是一个用于搜索字符串的 Linux/Unix 命令行工具,因此选项 ’ ^d ’ 过滤那些以 ’ d‘开头的字符串。
7.1. 将grep与ls命令一起使用
如果我们可以使用 ’ ls -l ‘列出所有文件和目录并将它们传递给 grep,我们可以过滤它们以仅保留如下目录:
$ ls -l | grep '^d'
drwxr-xr-x 33 HARDIK users 4096 Feb 12 2018 arch
drwxr-xr-x 3 HARDIK users 4096 Feb 12 2018 block
drwxr-xr-x 2 HARDIK users 200 Feb 12 2018 certs
drwxr-xr-x 4 HARDIK users 4096 Feb 12 2018 crypto
drwxr-xr-x 122 HARDIK users 8192 Feb 12 2018 Documentation
... ... ... ... ... ... ...
7.2. 将grep与dir命令一起使用
我们也可以将 grep 命令与 dir 命令一起使用,如上所示以列出目录:
$ dir | grep '^d'
drwxr-xr-x 33 HARDIK users 4096 Feb 12 2018 arch/
drwxr-xr-x 3 HARDIK users 4096 Feb 12 2018 block/
drwxr-xr-x 2 HARDIK users 200 Feb 12 2018 certs/
drwxr-xr-x 4 HARDIK users 4096 Feb 12 2018 crypto/
drwxr-xr-x 122 HARDIK users 8192 Feb 12 2018 Documentation/
... ... ... ... ... ... ...