2017-07-06 42 views
0

我需要检查图像是否有900x900像素的分辨率和文件名不允许包含_thumb_V巴什脚本IF条件

我试图用这个做line:
如果图片的像素为900x900像素且不包含_v或_thumb =>在文件扩展名之前将单词_thumb添加到文件名的末尾。

行了它的所有有关:

if file $picture | grep -q 900x900 && ! file $picture | grep -q _thumb && ! file $picture | grep -q _v; 

脚本:

#Change to current .sh directory 
cd -P -- "$(dirname -- "$0")" 
for picture in */*/Templates/*.jpg 
do 
    filename=${picture##*/} 
    filename1=$(echo "$filename" |sed 's/.\{4\}$//') 
    parent_dir="$(dirname -- "$(/usr/local/bin/realpath "$picture")")" 

    #Colors 
    red=`tput setaf 1` 
    green=`tput setaf 2` 
    magenta=`tput setaf 5` 
    reset=`tput sgr0` 


    if file $picture | grep -q 900x900 && ! file $picture | grep -q _thumb && ! file $picture | grep -q _v; 
     then 
      mv -v "$picture" "$parent_dir/"$filename1"_thumb.jpg" 
      echo "${green} [PASS] $filename1 Thumbnail 900x900 found and renamed ${reset}" 
     else 
      echo "${magenta} [WARNUNG] $filename1 contains _thumb already or is a _v picture or isn't 900x900 pixels ${reset}" 
     fi 
+0

问题是它不识别图片,即使它是900x900并且不包含关键字。 在此先感谢 –

+0

建议使用http://www.shellcheck.net/...例如,引用您的变量..你可以尝试'如果文件'$ picture“| grep -q'900x900''没有其他条件,看看它是否工作? – Sundeep

回答

0

我看到的几个问题。 #3,#4和#5是最重要的看看。在您的第一线

    1. 目标壳您需要与done
    2. 完成for循环你需要逃脱$filename1内双引号。周围的报价目前没有引用这个。
    3. 双引号该行中的变量
    4. 澄清如果您正在寻找图像大小或只是该文件中有900x900?原因grep -q 900x900找不到图像大小。正如其他人所提到的,您需要将它与imagemagik identify结合使用。

    随着修复:

    #!/bin/bash 
    #Change to current .sh directory 
    cd -P -- "$(dirname -- "$0")" 
    for picture in */*/Templates/*.jpg 
    do 
        filename=${picture##*/} 
        filename1=$(echo "$filename" |sed 's/.\{4\}$//') 
        parent_dir="$(dirname -- "$(/usr/local/bin/realpath "$picture")")" 
    
        #Colors 
        red=`tput setaf 1` 
        green=`tput setaf 2` 
        magenta=`tput setaf 5` 
        reset=`tput sgr0` 
    
    
        if file "$picture" | grep -q 900x900 && ! file "$picture" | grep -q _thumb && ! file "$picture" | grep -q _v; 
         then 
          mv -v "$picture" "$parent_dir/\"$filename1\"_thumb.jpg" 
          echo "${green} [PASS] $filename1 Thumbnail 900x900 found and renamed ${reset}" 
         else 
          echo "${magenta} [WARNING] $filename1 contains _thumb already or is a _v picture or isn't 900x900 pixels ${reset}" 
         fi 
    done 
    
  • 0

    不要使用 “文件$图片| grep的900x900”,因为你不知道,如果文件名包含900x900。我建议使用命令的识别存在于ImageMagick软件包像:

    if [[ "900 900" == $(identify -format '%w %h' "$picture") ]] ; then 
        if [[ $picture != *_v.jpg && $picture != _thumb.jpg ]] ; then 
        mv "$picture" "${picture%.jpg}_thumb.jpg" 
        fi 
    fi 
    

    我稍微用假设_V从规范偏离和_thumb似乎只是延长了。我认为避免像best_view.jpg这样的意外匹配更加明智。 PS:当文件名或dirnames中有空格时,请检查您的脚本是否正常工作。