sh脚本 递归删除当前子文件夹的所有的txt
时间: 2023-09-17 17:05:31 浏览: 68
### 回答1:
您可以使用以下sh脚本进行递归删除当前子文件夹中的所有txt文件:
```sh
find . -name "*.txt" -type f -delete
```
这将在当前文件夹及其子文件夹中查找所有名为"*.txt"的文件,并将其删除。
### 回答2:
可以使用以下的sh脚本来递归删除当前子文件夹中的所有txt文件:
```sh
#!/bin/bash
delete_txt_files() {
for file in "$1"/*; do
if [ -d "$file" ]; then
delete_txt_files "$file"
elif [ -f "$file" ] && [ "${file##*.}" = "txt" ]; then
rm "$file"
fi
done
}
delete_txt_files .
echo "已成功删除所有子文件夹中的txt文件。"
```
这个脚本定义了一个名为`delete_txt_files`的函数,它接受一个参数表示当前文件夹路径。在这个函数中,我们使用`for`循环遍历当前文件夹中的所有文件和子文件夹。如果遍历到的是一个子文件夹,我们会递归调用`delete_txt_files`函数,以进一步删除子文件夹中的txt文件。如果遍历到的是一个txt文件,我们会使用`rm`命令删除它。
最后,我们在脚本的最后调用`delete_txt_files`函数,并且打印一条消息表示成功删除了所有子文件夹中的txt文件。
### 回答3:
sh脚本用于递归删除当前子文件夹中的所有txt文件,可以通过以下命令实现:
#!/bin/bash
#递归删除当前子文件夹的所有txt
function delete_txt {
for file in "$1"/*; do
if [[ -d "$file" ]]; then
delete_txt "$file" #递归调用自身处理子文件夹
elif [[ -f "$file" && "${file##*.}" == "txt" ]]; then
rm "$file" #删除后缀为txt的文件
fi
done
}
#执行删除操作
delete_txt . #当前目录作为起始点
首先,定义了一个名为delete_txt的函数,每次调用该函数时会接收一个参数,该参数表示当前目录。
在函数中,使用for循环遍历当前目录下的所有文件和子目录。如果遍历到的文件是一个目录,则使用递归调用delete_txt函数,处理子目录中的文件。
如果遍历到的文件是一个普通文件,并且文件的后缀名是txt,则使用rm命令删除该文件。
最后,在脚本的最后一行,调用delete_txt函数来实现递归删除当前子文件夹中的所有txt文件。传入的参数为当前目录".",表示从当前目录开始递归删除txt文件。
这样,运行该脚本后,当前子文件夹中所有的txt文件都会被删除。
相关推荐
![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_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)
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)