Files
StudyDiary/60-Imports/64-AI/Linux:删除目录内所有文件,保留目录结构(保留父目录、所有子文件夹,只删文件).md

123 lines
2.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Linux:删除目录内所有文件,保留目录结构(保留父目录、所有子文件夹,只删文件)
# Linux:删除目录内 \\*\\* 所有文件,保留目录结构(保留父目录、所有子文件夹,只删文件)
> 需求:只删文件,**目录本身全部保留**,不删除文件夹。
>
>
## 核心命令(find)
### 方式 1:直接执行(推荐,一行命令)
```bash
# 将 /path/to/your_dir 替换为你的目标主目录
find /path/to/your_dir -type f -delete
```
- `-type f`:只匹配普通**文件**,不会匹配文件夹
- `-delete`:删除匹配到的文件,**所有子目录完整保留**
> ⚠️ 高危!先加 `-print` 预览要删哪些文件,确认无误再执行删除:
>
>
```bash
# 预览,只打印,不会删除
find /path/to/your_dir -type f -print
```
### 兼容老版本 find(部分旧系统不支持 `-delete`)
```bash
find /path/to/your_dir -type f -exec rm -f {} \;
```
---
## 区分:还要删除软链接文件?
上面 `-type f` **不会删除符号链接**。
如果希望同时删除普通文件 \+ 软链接:
```bash
find /path/to/your_dir \( -type f -o -type l \) -delete
```
## 不生效坑点说明
1. 不会删除隐藏文件?✅ `find` 默认会扫描 `.xxx` 隐藏文件,一并删除。
2. 不会删除文件夹,子目录全部原样保留。
3. 权限不足:前面加 `sudo`,注意风险。
---
# 写成小脚本 clear\_dir\_only\\\[\_files\.sh\]\(\_files\.sh\)
```bash
#!/bin/bash
if [ $# -ne 1 ];then
echo "用法: $0 目标目录"
exit 1
fi
TARGET="$1"
if [ ! -d "$TARGET" ];then
echo "错误:$TARGET 不是有效目录"
exit 1
fi
echo "即将删除目录【$TARGET】下全部文件,保留目录结构"
echo "预览待删除文件:"
find "$TARGET" -type f -print
read -p "确认删除?输入 y 确认:" ans
if [ "$ans" = "y" ];then
find "$TARGET" -type f -delete
echo "完成,仅删除文件,目录结构已保留"
else
echo "已取消操作"
fi
```
### 使用脚本
```bash
chmod +x clear_dir_only_files.sh
#传入要清理的目录
./clear_dir_only_files.sh /data/audiobooks
```
---
## ❌不要用这些错误写法
```bash
#错误!会把整个目录删掉
rm -rf /xxx/*
#错误!会删除子目录
find xxx -exec rm -rf {} \;
```
### 补充:如果你想删掉目录下的**空文件夹**(额外需求)
> 只删空目录,已有文件的目录不动
>
>
```bash
find /path/to/your_dir -type d -empty -delete
```
> 重要提醒:操作前强烈建议先执行预览命令,确认列表,再真实删除,避免误删。
>
>
> (注:部分内容可能由 AI 生成)