Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash grep两个整数并比较它们_Bash_Grep_Compare - Fatal编程技术网

Bash grep两个整数并比较它们

Bash grep两个整数并比较它们,bash,grep,compare,Bash,Grep,Compare,我正在尝试编写一个脚本,该脚本执行以下操作: 给定一个类似于“有5个苹果和3个桔子”的字符串 提取两个整数(5,3) 比较它们 我完成了摘录部分 NUM=echo $String | grep -o "[0-9]\+" 但是NUM是这样的: 5 3 \n input='There are 5 apples and 3 oranges' nums=($(grep -Eo '[0-9]+' <<< "$input")) 我尝试了${NUM[0]}和${NUM[@]}只是为了得

我正在尝试编写一个脚本,该脚本执行以下操作:

  • 给定一个类似于“有5个苹果和3个桔子”的字符串
  • 提取两个整数(5,3)
  • 比较它们
  • 我完成了摘录部分

    NUM=echo $String | grep -o "[0-9]\+"
    
    但是NUM是这样的:

    5
    3
    \n
    
    input='There are 5 apples and 3 oranges'
    nums=($(grep -Eo '[0-9]+' <<< "$input"))
    
    我尝试了
    ${NUM[0]}
    ${NUM[@]}
    只是为了得到第一个值,但没有成功


    有什么建议吗?

    您分配给
    NUM
    的方式不正确。 你文章中的
    grep
    模式也是如此。 这样写:

    5
    3
    \n
    
    input='There are 5 apples and 3 oranges'
    nums=($(grep -Eo '[0-9]+' <<< "$input"))
    

    我将通过进程替换和
    mapfile
    来实现这一点:

    $ mapfile -t nums < <(grep -Eo '[[:digit:]]+' <<< 'There are 5 apples and 3 oranges')
    $ declare -p nums
    declare -a nums='([0]="5" [1]="3")'
    

    $mapfile-t nums<带有
    GNU awk

    gawk '{if($1>$2){print $1">"$2}else if($1<$2){print $1"<"$2} else {print $1"="$2}}' FPAT='[0-9]+' <<<'There are 5 apples and 8 oranges'
    
    gawk'{if($1>$2){print$1”>“$2}else if($1带GNU awk的FPAT:

    $ echo 'There are 5 apples and 3 oranges' |
        awk -v FPAT='[0-9]+' '{print ($1 > $2 ? "greater" : "lesser")}'
    greater
    $ echo 'There are 2 apples and 3 oranges' |
        awk -v FPAT='[0-9]+' '{print ($1 > $2 ? "greater" : "lesser")}'
    lesser
    

    @我用这些案例的例子更新了我的答案。