我想编写一个脚本,它可以接受一个文件夹并删除该文件夹中子文件夹内的所有文件。
例如:
abc
- a.txt - b.txt
efg
- e.txt
x.txt
运行该脚本后,应删除a.txt、b.txt和e.txt,而不是x.txt(因为它不在文件夹内)。
例如:
abc
- a.txt - b.txt
efg
- e.txt
x.txt
运行该脚本后,应删除a.txt、b.txt和e.txt,而不是x.txt(因为它不在文件夹内)。
find
命令递归返回文件夹中的所有文件。
find ${dir} -name "*.txt" -delete
上述命令搜索存储在变量中的目录dir
中以.txt
结尾的文件并将其删除。但是如果您只想查找子目录中的文件呢?find ${dir}/*/ -name "*.txt" -delete
请注意,我们添加了/* /
以表示查找此文件夹内的所有文件夹。您还可以附加检查-type f
以确认我们正在删除文件而不是其他内容。使用 find
命令:
示例 test
文件夹结构:
$ tree test
test
├── abc
│ ├── a.txt
│ └── b.txt
├── efg
│ └── e.txt
└── x.txt
重要的命令:
find test -mindepth 2 -type f -delete
查看结果:
$ tree test
test
├── abc
├── efg
└── x.txt
这里是一个例子
。find */ -name *.txt -type f | xargs rm -f
find "$dir"
或者find "${dir}"
命令都是正确的,但是加上引号可以防止目录名中含有空格时被分割成多个单词;可以尝试使用带有空格的目录名进行测试。 - Charles Duffy