我有一个看起来像这样的输入文件

时间:2013-11-26 09:20:24

标签: shell awk

在我的程序中,我必须比较列之间的值。

  • 比较$3$1,打印$1
  • 中的最大值
  • 比较$3$2,打印来自$2
  • 的最小值
  • 还会比较$1[i]$1[i+1]

数据:

150;    145.15; 148;
149.43; 143.62; 148;
147.45; 141.95; 148;
147.09; 141.46; 148;
147.59; 141.49; 148;
147.22; 141.41; 148;
147.34; 141.33; 148;
147.54; 141.32; 148;
148.23; 141.36; 148;
149.04; 141.24; 148;

以下是代码:

#!/bin/bash  
awk '
BEGIN {
  FS=";";
}
{
  if(NR>1)
  {
    Max =  $1
    Min  = $2
    Com  = $3
    if(Max>Com)
    {
      NMax = Max
      if(Max>Com && NMax<Max)
      {
         NMax = Max 
      }
    }
    if(Com>Min)
    {   
      NMin = Min
      if(Min<Com && NMin<Min)
      {
        NMin = Min 
      }    
    }
  }
  if(NR>1)                
    printf "%9.2f;%9.2f;%9.2f;%9.2f;%9.2f;\n", $1,$2,$3,NMax,NMin
}' data.txt > out.txt

OutPut:

149.43;   143.62;   148.00;   149.43;   143.62;
147.45;   141.95;   148.00;   149.43;   141.95;
147.09;   141.46;   148.00;   149.43;   141.46;
147.59;   141.49;   148.00;   149.43;   141.49;
147.22;   141.41;   148.00;   149.43;   141.41;
147.34;   141.33;   148.00;   149.43;   141.33;
147.54;   141.32;   148.00;   149.43;   141.32;
148.23;   141.36;   148.00;   148.23;   141.36;
149.04;   141.24;   148.00;   149.04;   141.24;

但我想要输出外观

149.43;   143.62;   148.00;   148.23;   143.62;
147.45;   141.95;   148.00;   148.23;   143.62;
147.09;   141.46;   148.00;   148.23;   143.62;
147.59;   141.49;   148.00;   148.23;   143.62;
147.22;   141.41;   148.00;   148.23;   143.62;
147.34;   141.33;   148.00;   148.23;   143.62;
147.54;   141.32;   148.00;   148.23;   143.62;
148.23;   141.36;   148.00;   148.23;   143.62;
149.04;   141.24;   148.00;   148.23;   143.62;

1 个答案:

答案 0 :(得分:0)

你可以尝试

awk -f p.awk input.txt

其中input.txt是您的输入文件,p.awk

BEGIN {
  FS=";";
}

NR>1{
    if (NR==2) {
        NMax=$1
        NMin=$2
        a=$1
        b=$2
    }
    else {
        if($1>$3)
            NMax = $1
        if($3>$2)
            NMin = $2
        a=(NMax<a)?NMax:a;
        b=(NMin>b)?NMin:b;
    }
    a1[NR]=$1; a2[NR]=$2; a3[NR]=$3

}

END {
    for (i=2; i<=NR; i++)
        printf "%9.2f;%9.2f;%9.2f;%9.2f;%9.2f;\n", a1[i],a2[i],a3[i],a,b

}