用shell 递归子目录
时间: 2023-07-12 12:33:56 浏览: 63
在Linux Shell中,可以使用`find`命令递归遍历子目录,示例如下:
```bash
find /path/to/directory -type d -print
```
上述命令将遍历`/path/to/directory`目录下的所有子目录,并输出找到的目录名。
如果要同时遍历子目录中的文件,可以将命令中的`-type d`选项改为`-type f`选项,例如:
```bash
find /path/to/directory -type f -print
```
上述命令将遍历`/path/to/directory`目录下的所有文件(包括子目录中的文件),并输出找到的文件名。
如果要进一步操作找到的文件或目录,可以使用`-exec`选项,例如:
```bash
find /path/to/directory -type f -name "*.txt" -exec rm {} \;
```
上述命令将删除`/path/to/directory`目录下所有扩展名为`.txt`的文件(包括子目录中的文件)。其中,`{}`表示找到的文件名,`\;`表示命令结束符。
需要注意的是,`find`命令会递归遍历目录下的所有子目录,如果要限制遍历深度,可以使用`-maxdepth`选项,例如:
```bash
find /path/to/directory -maxdepth 1 -type f -print
```
上述命令将只遍历`/path/to/directory`目录下的文件,不会遍历子目录中的文件。
相关问题
shell脚本递归文件名
在Shell脚本中,可以使用递归的方式获取文件名。下面是一个示例代码,用于递归获取指定目录下的所有文件名:
```shell
#!/bin/bash
function recursive_files() {
local dir=$1
for file in "$dir"/*; do
if [ -f "$file" ]; then
echo "$file"
elif [ -d "$file" ]; then
recursive_files "$file"
fi
done
}
# 调用递归函数,传入目标目录作为参数
recursive_files "/path/to/directory"
```
上述代码定义了一个名为`recursive_files`的递归函数,该函数接受一个目录作为参数。在函数内部,使用`for`循环遍历目录下的所有文件和子目录。如果是文件,则直接输出文件名;如果是目录,则递归调用`recursive_files`函数。
你可以将`/path/to/directory`替换为你想要获取文件名的目录路径。运行脚本后,它将递归地输出指定目录下的所有文件名。
shell遍历目录及其子目录中的所有文件方法
在Shell中遍历目录及其子目录中的所有文件,常见的方法有使用`find`命令和使用递归函数。
一、使用find命令:
```
find <目录路径> -type f
```
其中,`<目录路径>`是需要遍历的目录的路径。通过`-type f`参数指定只查找文件,忽略目录。
例如,要遍历当前目录及其子目录中的所有文件,可以使用以下命令:
```
find . -type f
```
命令执行后,会输出所有符合条件的文件路径。
二、使用递归函数:
在Shell脚本中,可以使用递归函数来遍历目录及其子目录中的文件。
```shell
#!/bin/bash
function traverse_directory() {
for file in $1/*
do
if [ -d "$file" ] ; then
traverse_directory $file
else
echo "$file"
fi
done
}
traverse_directory <目录路径>
```
其中,`<目录路径>`是需要遍历的目录的路径。递归函数`traverse_directory`会遍历目录下的所有文件和子目录,如果是子目录则递归调用该函数,如果是文件则输出文件路径。
例如,要遍历当前目录及其子目录中的所有文件,可以将上述脚本保存为文件`traverse.sh`,然后使用以下命令执行:
```
bash traverse.sh
```
命令执行后,会输出所有文件的路径。
以上是两种常见的Shell遍历目录及其子目录中的所有文件的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)