繁体   English   中英

通过文件扩展名确定操作 | bash shell

[英]Determine an action by file extension | bash shell

我想通过我的数组中文件的文件扩展名来确定一个动作。 例如,如果数组匹配 *.zip 则执行 x。 该脚本不会位于存档路径中。

archive_path="$HOME/Downloads/"

compressed_files=("`find "$achieve_path" -iname "*.zip" -o -iname "*.rar" -o -iname "*.7z"`")

for files in "${compressed_files[@]}"; do
   echo "$files" ;

done

更新 1:这是我尝试过的另一种方法。 不返回错误,但也没有结果。

shopt -s nocasematch

dir="$HOME/Downloads/all/"

 for file in "$dir*.@(.zip|.rar|.7z)" ; do

   case "$file" in

  *.rar)
    echo "$file this is a rar file"
    ;;
  *.zip)
    echo "$file this is a zip file"
    #...
    ;;
  *.7z)
    echo "$file this is a 7z file"
    #...
    ;;
esac

done

解决方案:

测试平台: macOS Catalina

注意:将您的 bash 升级到最新版本,最新的 macOS 默认不附带最新版本的 bash。

#!/usr/bin/env bash


shopt -s nocasematch

dir="$HOME/Downloads/all/"

 for file in "$dir"* ; do

   case "$file" in

  *.rar)
    echo "$file this is a rar file"
    ;;
  *.zip)
    echo "$file this is a zip file"
    #...
    ;;
  *.7z)
    echo "$file this is a 7z file"
    #...
    ;;
esac

done

请参阅如何将“查找”命令结果作为数组存储在 Bash中,了解如何将find结果正确传递到 bash 数组中。

您可以像这样在for循环中匹配:

shopt -s nocasematch  # ignore upper/lower case in 'case' statement
for file in "${compressed_files[@]}" ; do
   case "$file" in
   *.zip)
      echo "do something with zip file $file"
      ;;
   *.rar)
      echo "do something else with rar file $file"
      ;;
   *)
      echo "handling file $file"
      ;;
   esac
done

除非你被旧版本的bash卡住,否则你根本不需要find

shopt -s globstar extglob nullglob nocasematch

for file in **/*.@(zip|rar|7z); do
     case $file in
       *.zip) ... ;;
       *.rar) ... ;;
       *.7z) ... ;;
     esac
done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM