文件名与shell脚本的大小写结构中的模式不匹配

zzzyeukh  于 2023-08-07  发布在  Shell
关注(0)|答案(1)|浏览(113)

我这个程序的目标是有效地重新安排随机文件在一个目录和地方,然后在各自的子目录的基础上,他们的格式,即音频文件被放置在audios目录等。到目前为止,匹配此文件的模式没有产生所需的结果,并且所有文件都被移动到others目录。
这里是代码

#!/bin/bash

# Get the path of the current directory
CURR_DIR="$(cd "$(dirname "$0")" && pwd)";
# SCRIPT_NAME="$(basename "${BASE_SOURCE[0]}")"
SCRIPT_NAME="$(basename "$0")"

echo "$SCRIPT_NAME"
# List the various file format and thier extensions 
LIST_DOCS=("doc" "docx" "pdf" "txt")
LIST_IMAGES=("jpg" "jpeg" "png" "gif")
LIST_AUDIOS=("mp3" "wav" "ogg" "aac" "m4a" "mp4" "wma" "aiff" "au" "vox")
LIST_VIDEOS=("mp4" "avi" "mov" "wmv" "mpeg" "mpg" "m4v" "mkv" "flv" "webm")

# Check if the images, videos, audios and documents directory exist
for dir_name in images videos documents audios others; do 
    if [ ! -d "$CURR_DIR/$dir_name" ]; then
        mkdir "$CURR_DIR/$dir_name"
    fi
done

# Read all the files and sort them
for file in "$CURR_DIR"/*
do 
    # Check if the current file is not the script itself
    if [ "$file" = "$CURR_DIR/$SCRIPT_NAME" ]; then 
        continue
    fi

    if [ -d "$file" ]; then
        continue
    fi

    # Move the file to the destination directory
    case "$file" in 
        *."${LIST_DOCS}")
            echo "Moving $file to documents/"
            mv $file "$CURR_DIR/documents/"
            ;;
        *."${LIST_IMAGES}")
            echo "Moving $file to documents/"
            mv $file "$CURR_DIR/images/"
            ;;
        *."${LIST_VIDEOS}")
            echo "Moving $file to documents/"
            mv $file "$CURR_DIR/videos/"
            ;;
        *."${LIST_AUDIOS}")
            echo "Moving $file to documents/"
            mv $file "$CURR_DIR/audios/"
            ;;
        *)
            echo "Moving $file to documents/"
            mv "$file" "$CURR_DIR/others"
            ;;
    esac

done

echo -e "Your files are now sorted :) \nProcess terminated"

字符串
我在case构造级别重新调整了模式,使文件与一个模式相匹配,该模式在前缀处包含一个通配符,并包含一个列表,该列表包含属于特定格式(如音频或电子邮件)的所有各种扩展名
*."${LIST_DOCS}是我使用的模式

csga3l58

csga3l581#

引用不带下标的数组变量等效于引用下标为0的变量。任何使用有效下标的变量引用都是法律的的,如果需要,bash将创建一个数组。
https://www.gnu.org/software/bash/manual/html_node/Arrays.html
因此,您的第一个案例实际上只检查*.doc
要存档您的目标,您可以循环遍历数组以查看扩展是否匹配。你可以从一个文件名中获取文件扩展名,只需要使用类似${filename##*.}的bash。(删除变量filename值中的任何内容,直到并包括最后一个点)

相关问题