如何實現(xiàn)查找目錄下同名但不同后綴名文件的shell腳本代碼-創(chuàng)新互聯(lián)

這篇文章主要介紹如何實現(xiàn)查找目錄下同名但不同后綴名文件的shell腳本代碼,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

專注于為中小企業(yè)提供網站設計、成都做網站服務,電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業(yè)商丘免費做網站提供優(yōu)質的服務。我們立足成都,凝聚了一批互聯(lián)網行業(yè)人才,有力地推動了上千余家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網站建設實現(xiàn)規(guī)模擴充和轉變。

因為后臺錄入的同事,上傳文件的時候,給文件取了相同的名字,但不同的后綴名,由于文件路徑非常深,大概十層左右,每一層又有幾十個文件,所以人工找起來非常麻煩,所以寫了個腳本,幫他們實現(xiàn)查找指定目錄下所有子目錄及文件,找出相同文件名,不同后綴的文件,然后,手動保留其中一個。


代碼如下:

#!/bin/bash 
#判斷一下腳本參數的問題 
if [ $# -ne 1 ];then 
   echo "Usage find_same.sh direcroty" 
   exit 
fi 
find $1 -type d > /tmp/dir.txt 
#將所有需要查詢的目錄本身和子目錄的名字存儲在一個臨時文件里 
#對每個目錄進行比較查詢 
while read dir 
do 
     find $dir -maxdepth 1 -type f > /tmp/file.txt 
     #將當前目錄下的所有文件存儲在臨時文件里 
     awk -F '/' '{print $NF}' /tmp/file.txt | awk -F '[.]' '{print $1}'| sort | uniq -d > /tmp/filename.txt 
     #把文件名字取出來,有同樣名字的就把名字放到/tmp/filename.txt里 
     line=`wc -l /tmp/filename.txt | awk '{print $1}'` 
     #判斷一下該文件里一共有多少行,每一行就是一個重名的文件名 
     #輸出 
     echo "The directory $dir including same name file: " 
     if [ $line -ge 1 ] ; then 
        while read name 
        do 
        filename=`grep $name /tmp/file.txt` 
                echo "$filename" 
                echo $filename >> /tmp/samefile.txt 
                #所有的記錄存放在這個文件里 
        done < /tmp/filename.txt 
      fi 
done < /tmp/dir.txt


模擬測試:

linux-8hij:/tmp/test # ll
total 4
-rw-r--r-- 1 root root    0 Mar  9 02:04 1.png
-rw-r--r-- 1 root root    0 Mar  9 02:04 1.txt
drwxr-xr-x 2 root root 4096 Mar  9 02:05 test1
linux-8hij:/tmp/test/test1 # ll
total 0
-rw-r--r-- 1 root root 0 Mar  9 02:05 11.jpg
-rw-r--r-- 1 root root 0 Mar  9 02:05 11.log
-rw-r--r-- 1 root root 0 Mar  9 02:05 2.log

運行結果:

linux-8hij:/tmp # ./find_name.sh /tmp
The directory /tmp including same name file:
The directory /tmp/.ICE-unix including same name file:
The directory /tmp/.X11-unix including same name file:
The directory /tmp/gconfd-root including same name file:
The directory /tmp/gconfd-root/lock including same name file:
The directory /tmp/gpg-PIEU09 including same name file:
The directory /tmp/test including same name file:
/tmp/test/1.txt
/tmp/test/1.png
The directory /tmp/test/test1 including same name file:
/tmp/test/test1/11.jpg
/tmp/test/test1/11.log

查看記錄:

linux-8hij:/tmp # cat /tmp/samefile.txt
/tmp/test/1.txt /tmp/test/1.png
/tmp/test/test1/11.jpg /tmp/test/test1/11.log

通過這個腳本可以實現(xiàn)指定目錄下同名但不同后綴名的查找,可以拓展為刪除指定的文件的腳本。

以上是“如何實現(xiàn)查找目錄下同名但不同后綴名文件的shell腳本代碼”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

網站標題:如何實現(xiàn)查找目錄下同名但不同后綴名文件的shell腳本代碼-創(chuàng)新互聯(lián)
文章路徑:http://bm7419.com/article26/dgoecg.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供定制網站企業(yè)網站制作、自適應網站網站內鏈、商城網站移動網站建設

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)