使用bash脚本对一个整数进行grep并将其与另一个进行比较



如果文件中的分数小于36,我有一个bash脚本可以将文件从一个位置复制到另一个位置。

我每个月运行一次这个脚本,以前它有效,但现在我得到了错误:

line 5: [: -lt: unary operator expected

这是脚本:

#!/bin/bash
for f in `ls $1/*.html`
do
        score=`grep -o -P '(?<=ADJ. SCORE: )-?[0-9]?[0-9]' $f`
        if [ $score -lt 36 ]
                then cp $f $2
        fi
done

我不确定操作系统是否重要;我使用的是OS X 10.7,过去我的bash脚本在Linux上运行得很好。

提前感谢!

他是对的,或者你可以做:

if [[ $score < 36 ]]
then
cp "$f" "$2"
fi

当没有匹配时会发生这种情况,$score就是空字符串。

一个简单的解决方案:

#!/bin/bash
for f in `ls $1/*.html`
do
        score=`grep -o -P '(?<=ADJ. SCORE: )-?[0-9]?[0-9]' $f`
        if [ -z $score ]
        then
            echo "No match in '$f'"
        else
            if [ "$score" -lt 36 ]
            then 
                cp "$f" "$2"
            fi
        fi
done

我认为您还需要更多地了解在shell脚本中引用的要求。

在我运行Mountain Lion 10.8.4版本的mac上,我看不到-P选项与grep。因此,您可以将perl用于(重新使用大部分脚本):

#!/bin/bash
for f in "${1}"/*.html; do    # Don't parse ls
  score=$(perl -ne "print $& if /(?<=ADJ. SCORE: )-?[0-9]?[0-9]/" "$f")
  if [ "$score" -lt 36 ]; then 
    cp "$f" $2
  fi
done

最新更新