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

linux shell中的遍历目录并删除目录下与目录名相同的文件,第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!

你可以参考如下实例代码:function getFile(file_name) 

    local f = assert(io.open(file_name, 'r'))

    local string = f:read("*all")

    f:close()

    return string

end function writeFile(file_name,string)

 local f = assert(io.open(file_name, 'w'))

 f:write(string)

 f:close()

end --从命令行获取参数, 如果有参数则遍历指定目录,没有参数遍历当前目录 if arg[1] ~= nil then

     cmd = "ls "..arg[1]

else

     cmd = "ls" end print("cmd", cmd)

--io.popen 返回的是一个FILE,跟c里面的popen一样 local s = io.popen(cmd)

local fileLists = s:read("*all")

print(fileLists)

while true do --从文件列表里一行一行的获取文件名 _,end_pos, line = string.find(fileLists, "([^\n\r]+.txt)", start_pos)

        if not end_pos then break end --    print ("wld", line) local str = getFile(line)

    --把每一行的末尾 1, 替换为 0, local new =string.gsub(str, "1,\n", "0,\n")

    --替换后的字符串写入到文件。以前的内容会清空     writeFile(line, new)

    start_pos = end_pos + 1 end


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

原文地址:https://54852.com/yw/8168639.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存