【问题标题】:Bash parsing outputs to variablesBash解析输出到变量
【发布时间】:2012-04-28 13:54:15
【问题描述】:

我正在尝试将我的照片分类为纵向和横向。我想出了一个打印 jpeg 大小的命令:

identify -format '%w %h\n' 1234.jpg 
1067 1600

如果我在 bash 脚本中使用它来将所有风景图片移动到另一个文件夹,我希望它类似于

#!/bin/bash
# loop through file (this is psuedo code!!)
for f in ~/pictures/
do
 # Get the dimensions (this is the bit I have an issue with)
 identify -format '%w %h\n' $f | awk # how do I get the width and height?
 if $width > $hieght
  mv ~/pictures/$f ~/pictures/landscape/$f
 fi
done

一直在查看 awk 手册页,但我似乎找不到语法。

【问题讨论】:

    标签: string bash awk jpeg


    【解决方案1】:

    你可以使用array:

    # WxH is a array which contains (W, H)
    WxH=($(identify -format '%w %h\n' $f))
    width=${WxH[0]}
    height=${WxH[1]}
    

    【讨论】:

    • 哇,关于 bash 的所有东西我都不知道 :)
    • 不要将美元符号放在作业的左侧。
    • 我有时会使用位置参数:set -- $(identify ...); width=$1; height=$2
    【解决方案2】:

    您不需要 AWK。做这样的事情:

    identify -format '%w %h\n' $f | while read width height
    do
        if [[ $width -gt $height ]]
        then
            mv ~/pictures/$f ~/pictures/landscape/$f
        fi
    done
    

    【讨论】:

    • 这就是票,在再次阅读 awk 人时,我确实想到可能有更好的方法。谢谢。
    • @Ne0:变量$f 应该在它出现的每个地方都被引用,因为图像文件名经常包含空格。由于您使用的是 Bash,因此您应该将其用于整数比较:if (( width > height ))。请注意,虽然在这种情况下它可以工作,但将命令传递到while 会创建一个子shell,这意味着当循环退出时,其中设置的任何变量值都将丢失。如果这很重要,请使用进程替换:while ... done < <(identify ...),并且在循环完成后变量值将可用。
    • while 循环有什么用? identify 似乎没有放多行。
    • 否则我需要对读取进行分组,如果在 () 内。循环做到了。基本上你是对的,但我使用 while 循环作为许多情况的单一解决方案。这很方便:-)
    【解决方案3】:
    format=`identify -format '%w %h\n' $f`;
    height=`echo $format | awk '{print $1}'`;
    width=`echo $format | awk '{print $2}'`;
    

    【讨论】:

      【解决方案4】:

      傻瓜,现在是“doh,明显的”:

      # use the identify format string to print variable assignments and eval
      eval $(identify -format 'width=%w; height=%h' $f)
      

      【讨论】:

        猜你喜欢
        • 2015-11-08
        • 2022-11-24
        • 1970-01-01
        • 2020-07-14
        • 1970-01-01
        • 2016-04-28
        • 2013-08-29
        • 2020-09-30
        • 1970-01-01
        相关资源
        最近更新 更多