【问题标题】:Write some "if-statement"写一些“if语句”
【发布时间】:2018-05-22 03:10:23
【问题描述】:

我想在“if-statement”中写一个脚本

./simulations/文件夹中有很多.html文件,在html文件中写end balance如下:

'期末余额:1000.00000000 (0.00%)'

'期末余额:19.21977440 (-98.08%)'

'期末余额:1135.80974233 (13.58%)'

我只想找到'期末余额:....... (...%)'

如果结束余额为1000或更低 echo 'end balance 100 0r lwss',如果更高,'echo end balance greater than 1000'。

像这样:

if [ "$(egrep -n 'end balance: [0-9.]' ./simulations/*.html)" -gt 1000 ]; then echo ' end balance bigger than 1000 ' else echo ' end balance less than 1000 ' fi

【问题讨论】:

  • 这个脚本有什么问题/错误?

标签: bash shell if-statement grep


【解决方案1】:

如果你这样做:

egrep -n 'end balance: [0-9.]' <<< 'end balance: 1135.80974233 (13.58%)'

你会得到:

1:end balance: 1135.80974233 (13.58%)

要比较数字,你必须在左右两边都有数字,所以我建议下面的 if 语句:

if (( $(grep -o 'end balance: [0-9]\{1,\}' ./simulations/*.html | awk '{print $3}') > 1000 ))

如果您想对 ./simulations/ 中的每个文件执行此操作,请使用循环:

IFS=$'\n'
for i in "$( ls -1 ./simulations/ | grep html$ )"
do
    if (( $(grep -o 'end balance: [0-9]\{1,\}' "$i" | awk '{print $3}') > 1000 ))
    then
        echo "end balance bigger than 1000"
    else
        echo "end balance less than 1000"
    fi
done

下面的命令:

grep -o 'end balance: [0-9]\{1,\}' <<< 'end balance: 1135.80974233 (13.58%)' | awk '{print $3}

现在将打印: 第1135章

【讨论】:

    【解决方案2】:

    您的条件失败,因为命令替换的输出不是整数。它也不是在每个文件的基础上应用的。

    在元代码中,您要查找的内容可能更像是:

    for every HTML file, loop
      Check the balance at the end of the file.
        If it's greater than 1000, do one thing,
        Otherwise, do something else.
    end loop
    

    在带有 grep 的 bash 中,这可能类似于:

    for f in simulations/*.html; do
        if egrep -q 'end balance: (1000|[0-9]{3})\>' "$f"; then
            echo "$f: end balance > 1000"
        else
            echo "$f: end balance <= 1000 or missing"
        fi
    done
    

    如果您想从文件中提取数字以进行 numeric 比较而不是使用正则表达式,那么这可能会起作用:

    for f in simulations/*.html; do
        n="$(egrep -o 'end balance: [0-9]+' "$f" | grep -o '[0-9]*')"
        if [[ -z "$n" ]]; then
            echo "$f: no balance found"
        elif [[ $n -gt 1000 ]]; then
            echo "$f: end balance > 1000"
        else
            echo "$f: end balance <= 1000"
        fi
    done
    

    在这两种情况下,每个处理的 HTML 文件都会有一行输出。

    【讨论】:

      【解决方案3】:

      感谢各位大师的回复

      EB=$(grep 'end balance:' ./simulations/*.html) if [[ $(cut -d. -f1 <<<"$EB" | tr -cd [0-9]) -gt 1000 ]]; then echo "end balance bigger than 1000" else echo "end balance less than 1000" fi

      我用这个

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-16
        • 2011-09-12
        • 2016-04-09
        相关资源
        最近更新 更多