linux shell中的遍历目录并删除目录下与目录名相同的文件

2024-11-16 02:54:17
推荐回答(1个)
回答1:

先设定实验环境:
#

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!