2014-10-02 91 views
3

我正在嘗試創建一個小型bash腳本,該腳本基本上通過包含數百個子目錄的目錄進行查看。在其中一些子目錄中包含一個textfile.txt和一個htmlfile.html,其中名稱textfile和htmlfile是可變的。unix bash找到帶有2個顯式文件擴展名的文件目錄

我只關心具有.txt和.html兩個子目錄,所有其他子目錄都可以忽略。

我再要列出所有的.html文件和.txt文件是在同一個子目錄

這似乎是一個很簡單的問題來解決,但我很茫然。所有我真正能夠工作的是一行代碼,它可以輸出具有.html文件或.txt的子目錄,而且與實際的子目錄無關,並且我在bash腳本中很新,所以我不能去任何進一步

任何幫助將提前不勝感激

#!/bin/bash 

files="$(find ~/file/ -type f -name '*.txt' -or -name '*.html')" 

for file in $files 
do 
echo $file 

done 

感謝

+0

後你有什麼至今。 – Deanie 2014-10-02 22:58:00

+0

以上更新,謝謝 – skevthedev 2014-10-02 23:01:21

+1

我覺得應該有辦法做到這一點與發現本身,但我正在努力想到現在可能是什麼。這意味着我得到的最好的答案(我現在沒有時間寫出來)會涉及到使用'-type f \(-name -o -name \)-printf'%h \ n' '然後通過管道將其awk/sort + uniq -c查找具有多個輸出項的結果。 – 2014-10-02 23:11:30

回答

1

您可以使用-o

#!/bin/bash 

files=$(find ~/file/ -type f -name '*.txt' -o -name '*.html') 

for file in $files 
do 
echo $file 

done 
+0

'-or' *是*'-o'只是不是POSIX。 – 2014-10-03 00:37:18

1
#!/bin/bash 

#A quick peek into a dir to see if there's at least one file that matches pattern 
dir_has_file() { dir="$1"; pattern="$2"; 
    [ -n "$(find "$dir" -maxdepth 1 -type f -name "$pattern" -print -quit)" ] 
} 

#Assumes there are no newline characters in the filenames, but will behave correctly with subdirectories that match *.html or *.txt 
find "$1" -type d|\ 
    while read d 
    do 
    dir_has_file "$d" '*.txt' && 
    dir_has_file "$d" '*.html' && 
    #Now print all the matching files 
    find "$d" -maxdepth 1 -type f -name '*.txt' -o -name '*.html' 
done 

此腳本將根目錄視爲第一個參數($ 1)。

2

find命令會檢查每一個子目錄,如果它有htmltxt文件,它列出了所有的人:

find . -type d -exec env d={} bash -c 'ls "$d"/*.html &>/dev/null && ls "$d"/*.txt &>/dev/null && ls "$d/"*.{html,txt}' \; 

說明:

  • find . -type d

    這尋找所有子目錄es當前目錄。

  • -exec env d={} bash -c '...' \;

    這將設置環境變量d查找到的子目錄的值,然後執行被包含在單引號內bash命令(見下文)。

  • ls "$d"/*.html &>/dev/null && ls "$d"/*.txt &>/dev/null && ls "$d/"*.{html,txt}

    這是所執行的bash命令。它由三個陳述組成。首先檢查目錄d是否有任何html文件。如果是這樣,第二個語句將運行,並檢查是否有任何txt文件。如果是,則執行最後一條語句,並列出目錄d中的所有html和txt文件。

此命令對包含空格,製表符或其他困難字符的所有文件和目錄名是安全的。

1

test命令是你需要什麼檢查每個文件的每個子目錄的存在:

find . -type d -exec sh -c "if test -f {}/$file1 -a -f {}/$file2 ; then ls {}/*.{txt,html} ; fi" \; 

其中$file1$file2是兩個.txt和.html文件,你正在尋找。

2

你可以通過與globstar選項遞歸搜索做到這一點:

shopt -s globstar 
for file in **; do 
    if [[ -d $file ]]; then 
     for sub_file in "$file"/*; do 
      case "$sub_file" in 
       *.html) 
        html=1;; 
       *.txt) 
        txt=1;; 
      esac 
     done 
     [[ $html && $txt ]] && echo "$file" 
     html="" 
     txt="" 
    fi 
done 
相關問題