awk根据file1中的匹配来划分字段



我正在尝试使用awk执行以下步骤

  1. 查找file1file2之间的匹配字段$1字符串
  2. 如果$1字符串匹配,则$2 in file1除以$3 in file2(即x,它是向上取整的3个重要数字)
  3. x乘以100
  4. 从100中减去每个x,这就是%

文件1

USH2A 21
GIT1 357
PALB2 3

文件2

GIT1 21 3096
USH2A 71 17718
PALB2 13 3954

awk

awk 'NR==FNR{a[$1]=$1;next;}{if ($1 in a) print $1, $2/a[$3];else print;}' file2 file1 > test
awk: cmd. line:1: (FILENAME=search FNR=2) fatal: division by zero attempted
awk 'NR==FNR{a[$1]=$1;next;}{if ($1 in a) print $1, $2/a[$3];else print;}' file1 file2 > test
awk: cmd. line:1: (FILENAME=search FNR=1) fatal: division by zero attempted

示例

USH2A match is found so (21/17718)*100 = 0.11  and 100-0.11 = 99.99%
GIT1 match is found so (357/3096)*100 = 11.53 and 100-11.53 = 88.47%
PALB2 match is found so (3/3954) *100 =  0.07 and 100-0.7 = 99.93%

我在代码中一行一行地进行,可以看到我已经收到了错误。谢谢:)。

awk前往救援!

$ awk 'function ceil(v) {return int(v)==v?v:int(v+1)}
        NR==FNR{f1[$1]=$2; next} 
       $1 in f1{print $1, ceil(10000*(1-f1[$1]/$3))/100 "%"}' file1 file2
GIT1 88.47%
USH2A 99.89%
PALB2 99.93%

注意,awk中没有舍入,因此为该任务定义了ceil函数。

$ cat tst.awk
NR==FNR { a[$1]=$3; next }
$1 in a {
    x = (a[$1] ? ($2*100)/a[$1] : 0)
    printf "%s match is found so (%d/%d) *100 =  %.2f and 100-%.2f = %.2f%%n", $1, $2, a[$1], x, x, 100-x
}
$ awk -f tst.awk file2 file1
USH2A match is found so (21/17718) *100 =  0.12 and 100-0.12 = 99.88%
GIT1 match is found so (357/3096) *100 =  11.53 and 100-11.53 = 88.47%
PALB2 match is found so (3/3954) *100 =  0.08 and 100-0.08 = 99.92%

最新更新