如何在 shell/perl 中根据条件将文件移动到新创建的目录中

如何在 shell/perl 中根据条件将文件移动到新创建的目录中

这是一堆音乐文件和目录。

需要同时对多个目录执行以下操作:

  1. 如果该目录包含“.jpg”文件,则创建一个新目录“Covers”并将这些文件移入其中。
  2. 如果该目录不包含任何“.jpg”文件,则不要创建“Covers”目录
  3. 如果目录已包含“Covers”目录,则不要创建“Covers”目录

答案1

bash

#!/bin/bash
shopt -s nullglob
for dir; do
    [[ -d $dir ]] || continue
    jpgs=( "${dir}"/*.jpg )
    if (( "${#jpgs[@]}" )); then
        [[ -d ${dir}/Covers ]] || mkdir "${dir}/Covers"
        # Avoiding race condition by not reusing the jpgs array
        for jpg in "${dir}"/*.jpg; do
            mv "$jpg" "${dir}/Covers"
        done
    fi
done

答案2

我还是个菜鸟,但这是我的:

#!/bin/bash
current_directory=$(pwd)
#echo $current_directory
(find -maxdepth 1 -type d -name '*' ! -name '.*' -printf '%f\n')>filelist
number=$(find -maxdepth 1 -type d -name '*' ! -name '.*' -printf '%f\n' | wc -l)
for iteration in `seq $number`
do
    fname=$(head -1 filelist)
    sed 1d < filelist > filelist2
    mv filelist2 filelist
    cd "$fname"
    if [ -z $(ls | grep -i jpg) ]
    then echo "Doing nothing as there are no JPG files....."
    else
        total=$(ls -l|grep -i jpg | wc -l)
        mkdir -p Covers
        mv *.jpg Covers
        echo "Moved $total JPG Files....."
    fi
    cd "$current_directory"
done  

只需进入主音乐目录并执行此脚本即可。

无需传递任何参数

编辑:以前很草率。现在更马虎了。但我认为它会起作用。

答案3

#!/bin/bash  

SAVEIFS=$IFS  
IFS="\n\b"  
#-----------------------------------------------------------------------------  

#work in current dir if work path was not provided  
[ $# -eq 0 ] && search_path="." || search_path="$1"  


# files to be moved, more extensions can be added  
wildcard="*[jpg|JPG]"  


move_jpg() {  
    # create "Covers" if it doesn't exist  
    [ -d "$1/Covers" ] && echo -n " ... " || { echo -n " ...create Covers ";   mkdir "$1/Covers" }  

    mv "$1/$wildcard" "$1/Covers/$wildcard"  
    echo "... files moved"  
}  



for d in "$search_path/*/"; do  

    echo -n "testing <$d>   "  

    [ -e "$d/$wildcard" ] && ${move_jpg "$d"} || echo "...Not found <$wildcard>"  

done  



#-----------------------------------------------------------------------------  
IFS=$SAVEIFS  

相关内容