据我所知,ls -R会显示目录列表。但是为什么它是递归的呢?如何在过程中使用递归?
发布于 2017-01-23 18:59:47
首先,让我们定义一个任意文件夹结构:
.
├── a1 [D]
│ ├── b1 [D]
│ │ ├── c1
│ │ ├── c2 [D]
│ │ │ ├── d1
│ │ │ ├── d2
│ │ │ └── d3
│ │ ├── c3
│ │ ├── c4
│ │ └── c5
│ └── b2 [D]
│ ├── c6
│ └── c7
├── a2 [D]
│ ├── b3 [D]
│ │ ├── c8
│ │ └── c9
│ └── b4 [D]
│ ├── c10
│ └── c11
├── a3 [D]
│ ├── b5
│ ├── b6
│ └── b7
└── a4 [D]当我们执行ls时,我们只获得基本文件夹的输出:
a1 a2 a3 a4然而,当我们调用ls -R时,我们得到了一些不同的信息:
.:
a1 a2 a3 a4
./a1:
b1 b2
./a1/b1:
c1 c2 c3 c4 c5
./a1/b1/c2:
d1 d2 d3
./a1/b2:
c6 c7
./a2:
b3 b4
./a2/b3:
c8 c9
./a2/b4:
c10 c11
./a3:
b5 b6 b7
./a4:如您所见,它在基本文件夹上运行ls,然后运行所有子文件夹。和所有的孙子文件夹,无限的。实际上,该命令递归地遍历每个文件夹,直到到达目录树的末尾。此时,它会返回到树中的一个分支,并对任何子文件夹(如果有的话)执行相同的操作。
或者,在伪码中:
recursivelyList(directory) {
files[] = listDirectory(directory) // Get all files in the directory
print(directory.name + ":\n" + files.join(" ")) // Print the "ls" output
for (file : files) { // Go through all the files in the directory
if (file.isDirectory()) { // Check if the current file being looked at is a directory
recursivelyList(directory) // If so, recursively list that directory
}
}
}因为我可以,一个同样的参考Java实现。
发布于 2017-01-23 18:58:18
想想看,“递归”命令对目录及其文件和目录以及它们的文件都有意义.
……在此情况下,列出任何子目录的内容.在命令的论点(S)下存在的
发布于 2017-01-24 20:55:01
这里有一个简单的解释,因为当涉及到显示子目录的内容时,相同的函数已经知道如何处理一个目录。因此,它只需要在每个子目录上调用自己就可以得到结果!
在伪代码中,它看起来如下所示:
recursive_ls(dir)
print(files and directories)
foreach (directoriy in dir)
recursive_ls(directory)
end foreach
end recursive_lshttps://askubuntu.com/questions/875370
复制相似问题