在linux如何批量删除多级目录下同一格式的文件呢?

在linux如何批量删除多级目录下同一格式的文件呢?,第1张

在linux批量删除多级目录下同一格式的文件,可采用find

+

exec命令组合:

如在删除old目录下的,所有子目录中,后缀为.l的文件方法为:

find

old

-type

f

-name

"*.l"

-exec

rm

-f

{}

\

说明:

old:待查找的开始目录,搜索其下的子目录

-type

f

:

文件类型为普通文件

若查找的目标文件是目录,则用

-type

d

-name

"*.l"

:

表示文件名与"*.l"匹配,双引号不能少!

rm

-f

{}

:

删除时,不提示,{}表示查找到的文件

先设定实验环境:

#

5

目录,每个目录下,造

3

文件和两个子目录如下:

cd

$home/tmp

for

i

in

d1

d2

d3

d4

d5

do

mkdir

-p

$i

touch

$i/1.txt

$i/2.txt

$i/3.txt

mkdir

-p

$i/tmp1

$i/tmp2

done

#

检验测试环境:

$

ls

-lr

d1

total

0

-rw-r--r--

1

wenlee

comm

0

dec

22

10:35

1.txt

-rw-r--r--

1

wenlee

comm

0

dec

22

10:35

2.txt

-rw-r--r--

1

wenlee

comm

0

dec

22

10:35

3.txt

drwxr-sr-x

2

wenlee

comm

256

dec

22

10:35

tmp1/

drwxr-sr-x

2

wenlee

comm

256

dec

22

10:35

tmp2/

#

利用下列脚本来实现你要做的:

cd

$home/tmp

for

i

in

*/1.txt

do

echo

"found

$i,

save

$i

and

remove

everything

else

under

$(dirname

$i)/"

save_this_file=$(basename

$i)

curr_dir=$(dirname

$i)

#

把这个1.txt暂时存到/tmp里面去,为了避免已经有同样的档案名称在/tmp,加上$$

(i.e.

pid)

mv

$i

/tmp/${save_this_file}.$$

rm

-rf

$curr_dir

mkdir

-p

$curr_dir

mv

/tmp/${save_this_file}.$$

$curr_dir

done

#

屏幕执行输出如下:

found

d1/1.txt,

save

d1/1.txt

and

remove

everything

else

under

d1/

found

d2/1.txt,

save

d2/1.txt

and

remove

everything

else

under

d2/

found

d3/1.txt,

save

d3/1.txt

and

remove

everything

else

under

d3/

found

d4/1.txt,

save

d4/1.txt

and

remove

everything

else

under

d4/

found

d5/1.txt,

save

d5/1.txt

and

remove

everything

else

under

d5/

#

复验实验环境:

$

ls

-l

d?/*

-rw-r--r--

1

wenlee

comm

0

dec

22

10:35

d1/1.txt

-rw-r--r--

1

wenlee

comm

0

dec

22

10:35

d2/1.txt

-rw-r--r--

1

wenlee

comm

0

dec

22

10:35

d3/1.txt

-rw-r--r--

1

wenlee

comm

0

dec

22

10:35

d4/1.txt

-rw-r--r--

1

wenlee

comm

0

dec

22

10:35

d5/1.txt

ok?

thanks!


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/8394872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-16
下一篇 2023-04-16

发表评论

登录后才能评论

评论列表(0条)

保存