【问题标题】:bash check all file in a directory for their extensionbash 检查目录中的所有文件的扩展名
【发布时间】:2023-03-12 10:12:02
【问题描述】:

我正在编写一个 shell 脚本,通过用户输入读取给定目录中的所有文件,然后计算有多少具有该扩展名的文件。我刚开始学习 Bash,我不确定为什么它没有找到文件或读取目录。我只举了 2 个例子,但我的计数总是 0。

这就是我运行脚本的方式

$./check_ext.sh /home/user/temp

我的脚本 check_ext.sh

#!/bin/bash

count1=0
count2=0

for file in "ls $1"
do
if [[ $file == *.sh ]]; then 
    echo "is a txt file"
    (( count1++ ))
elif [[ $file == *.mp3 ]]; then
    echo "is a mp3 file"
    (( count2++ ))
fi  
done;

echo $count $count2

【问题讨论】:

  • 如果你只是想解决一个问题find 可以为你做这件事。如果您正在尝试学习 bash 编程,请按好先生。

标签: bash shell ubuntu


【解决方案1】:

"ls $1" 不会在 $1 上执行 ls,它只是一个普通字符串。命令替换语法为$(ls "$1")

不过没必要用ls,直接用globbing:

count1=0
count2=0

for file in "$1"/*; do
   if [[ $file == *.sh ]]; then 
       echo "is a txt file"
       (( count1++ ))
   elif [[ $file == *.mp3 ]]; then
       echo "is a mp3 file"
       (( count2++ ))
   fi  
done

echo "counts: $count1 $count2"

for file in "$1"/* 将遍历$1 表示的目录中的所有文件/目录


编辑:在目录中递归执行:

count1=0
count2=0

while IFS= read -r -d '' file; do
   if [[ $file == *.sh ]]; then 
       echo "is a txt file"
       (( count1++ ))
   elif [[ $file == *.mp3 ]]; then
       echo "is a mp3 file"
       (( count2++ ))
   fi  
done < <(find "$1" -type f -print0)

echo "counts: $count1 $count2"

【讨论】:

  • 非常感谢。是否可以读取其子文件夹?就像“/home/user/temp/sub/sub”中有文件一样
  • 只需像这样运行循环:for file in "$1"/* "$1"sub/*; do 但如果你想要所有子文件夹,那么我建议使用find
  • 对不起,我更改了代码 'FILES=$(find $1) for file in $FILES)' 但没有循环 for 循环。正在读取整个目录而不是单个文件
【解决方案2】:

POSIXly:

count1=0
count2=0

for f in "$1"/*; do
  case $f in
     (*.sh) printf '%s is a txt file\n' "$f"; : "$((count1+=1))" ;;
    (*.mp3) printf '%s is a mp3 file\n' "$f"; : "$((count2+=1))" ;;
  esac
done

printf 'counts: %d %d\n' "$count1" "$count2"

【讨论】:

    【解决方案3】:

    您也可以为此使用 Bash 数组:如果您只想处理扩展 shmp3

    #!/bin/bash
    
    shopt -s nullglob
    
    shs=( "$1"/*.sh )
    mp3s=( "$1"/*.mp3 )
    
    printf 'counts: %d %d\n' "${#shs[@]}" "${#mp3s[@]}"
    

    如果你想处理更多的扩展,你可以概括这个过程:

    #!/bin/bash
    
    shopt -s nullglob
    
    exts=( .sh .mp3 .gz .txt )
    counts=()
    
    for ext in "${exts[@]}"; do
        files=( "$1"/*."$ext" )
        counts+=( "${#files[@]}" )
    done
    
    printf 'counts:'
    printf ' %d' "${counts[@]}"
    echo
    

    如果你想处理所有扩展(使用关联数组,在 Bash ≥4 中可用)

    #!/bin/bash
    
    shopt -s nullglob
    
    declare -A exts
    
    for file in "$1"/*.*; do
        ext=${file##*.}
        ((++'exts[$ext]'))
    done
    
    for ext in "${!exts[@]}"; do
        printf '%s: %d\n' "$ext" "${exts[$ext]}"
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多