Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.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
Shell 在文件中打印大小数字_Shell_Sorting_Awk_Grep - Fatal编程技术网

Shell 在文件中打印大小数字

Shell 在文件中打印大小数字,shell,sorting,awk,grep,Shell,Sorting,Awk,Grep,我已经做了这些函数,但是正在打印负数:第一个函数忽略了-符号,所以它显示了最大的数字,但是它应该打印最大的正数。有没有办法解决这个问题 样本输入: function greater { grep -Eo '[0-9]*' $1 | sort -rn | head -n 1 } function lesser { grep -Eo '\-[0-9]*' $1 | sort -n | head -n 1 } 样本输出: -100 -90 95 10 -20 500 400 300 200

我已经做了这些函数,但是正在打印负数:第一个函数忽略了-符号,所以它显示了最大的数字,但是它应该打印最大的正数。有没有办法解决这个问题

样本输入:

function greater {
  grep -Eo '[0-9]*' $1 | sort -rn | head -n 1
}

function lesser {
  grep -Eo '\-[0-9]*' $1 | sort -n | head -n 1
}
样本输出:

-100 -90 95
10 -20
500 400 300 200 600

(较小的正在完美工作。)

我建议不要使用
grep+sort | head
两次,而是使用
gnu awk
并在一个命令中同时获得
max
min
会更有效:

awk-vrs='[:space:]+''
NR==1{max=min=$1}
$1>max{max=$1}
最小值>$1{min=$1}
结束{打印“max=”max,“min=”min}文件
最大值=600最小值=-100
其中
文件
数据为:

cat文件
-100 -90 95
10 -20
500 400 300 200 600
或使用任何版本的awk:

tr'[:blank:][''\n'max{max=$1}min>1{min=$1}END{print“max=”max,“min=”min}'

对于展示的示例,您也可以尝试以下内容。简单的解释是;使用xargs打印1列中的所有元素,然后将其作为标准输入传递给
awk
,在标准输入中,通过读取程序结束块处的整个输入_文件来查找最小值和最大值,并在其中打印两个值

Greater: 600
Lesser: -100
单独使用任何awk:

xargs -n1  <<< "$var" | awk 'FNR==1{max=min=$0} max>$0{max=$0} min<$0{min=$0} END{print max,min}'
awk'
NR==1{min=max=$1}

{for(i=1;i扩展您的方法

awk '
    NR==1 { min=max=$1 }
    { for (i=1; i<=NF; i++) {if ($i<min) min=$i; if (max<$i) max=$i} }
    END { printf "Greater: %d\nLesser: %d\n", max, min }
' file
Greater: 600
Lesser: -100

$tr-s'\\n我见过一些类似的示例,但它只适用于单个列($1)。但是数字可能不止一列,因此代码对我不起作用。我编辑了输入。嘿,我尝试在一个只有两个数字的文件中使用相同的数字,而较小的数字则不打印任何内容。为什么?
min
需要更正,请检查编辑的答案
grep-Eo-->-?[0-9]*“$1 | sort-n | tail-n1
grep-Eo——”-?[0-9]*“$1 | sort-n | head-n1
awk '
    NR==1 { min=max=$1 }
    { for (i=1; i<=NF; i++) {if ($i<min) min=$i; if (max<$i) max=$i} }
    END { printf "Greater: %d\nLesser: %d\n", max, min }
' file
Greater: 600
Lesser: -100
$ tr -s ' ' \\n <file | sort -n | sed -n '1s/.*/min: &/p;$s/.*/max: &/p'

min: -100
max: 600