应用场景:写了不少版的文档,定稿后只保留终稿,草稿状的都删除。linux
以下目录结构,删除root_dir下文件名称包含草稿的全部文件shell
/root_dir 草稿_1.txt 草稿_2.txt 终稿_1.txt 终稿_2.txt /child_dir child_草稿_1.txt child_草稿_2.txt child_终稿_1.txt child_终稿_2.txt /child_dir_2 child_2_草稿_1.txt child_2_草稿_2.txt child_2_终稿_1.txt child_2_终稿_2.txt
这里须要层层遍历文件夹,如root_dir中包含了文件夹child_dir。bash
#!/bin/bash cd root_dir for file in `ls .` do if [ -f $file ] then rm *草稿* fi if [ -d $file ] then echo $file 为目录 cd $file for f in `ls .` do if [ -f $f ] then rm *草稿* fi done cd .. fi done
删除完毕。post
cd root_dir find . -name "*未完*" -exec rm -f {} \;
删除完毕。code
注意:必定要保证进入了须要删除文件的目录,该命令没法撤回ip
find命令参数可查element
#!/bin/bash function getdir(){ for element in `ls $1` do dir_or_file=$1"/"$element if [ -d $dir_or_file ] then getdir $dir_or_file fi else if [[ $element == 【未完】* ]] then rm $dir_or_file echo $dir_or_file fi fi done } root_dir="_posts" getdir $root_dir
这里删除要使用全路径,不然会报错找不到文件。文档