ディレクトリのファイル拡張子を確認するBashスクリプト

ディレクトリのファイル拡張子を確認するBashスクリプト
#!/bin/bash
#Number for .txt files
txtnum=0
#Number of .sh files
shnum=0

for file in "SOME_PATH";do
  #if file has extension .txt
   if [[ $file ==* ".txt"]]
   then 
    #increment the number of .txt files (txtnum)
    txtnum++
   elif [[ $file ==* ".sh"]]
   then 
    #increment the number of .sh files (shnum)
    shnum++
   fi
echo "Number of files with .txt extension:$txtnum"
echo "Number of files with .sh extension:$shnum"

上記のコードは機能しませんが、私が望むロジックをレンダリングします。

初心者の場合、bashコマンドが正しくない可能性があります。

ベストアンサー1

編集されているため、明確に言うことはできませんが、ディレクトリ内のファイルに展開するには、SOME_PATH引用符のないglobを含める必要があります。*それは次のとおりです。

/path/to/*

Next は[[ $file ==* ".txt"]]無効です。特に==*有効な比較演算子ではありません。=~同様に正規表現の比較を行うことができますが、[[ $file =~ .*\.txt ]]個人的には拡張子を最初に抽出して個別に比較します。

以下はshnum++効果がありません。シェル算術複合コマンド内でコマンドを実行する必要があります((。例:((shnum++))

done最後に、ループの終了ステートメントがありませんfor


以下は、必要な操作を実行するいくつかの操作コードです。

#!/bin/bash

txtnum=0
shnum=0

for file in /path/to/files/*; do
    ext="${file##*.}"
    if [[ $ext == txt ]]; then
        ((txtnum++))
    elif [[ $ext == sh ]]; then
        ((shnum++))
    fi
done

printf 'Number of .txt files: %d\n' "$txtnum"
printf 'Number of .sh files: %d\n' "$shnum"

おすすめ記事