繁体   English   中英

bash中的多个/分隔列

[英]Multiple/divide columns in bash

我的数据框看起来像这样:

ERR843978.19884 13 51 51
ERR843978.2880 10 49 51
ERR843978.10002 7 48 55
ERR843978.1158 8 45 54
ERR843978.4671 14 62 60
ERR843978.83 15 56 70
ERR843978.9406 8 56 39
ERR843978.8383 12 59 43
ERR843978.8916 6 51 42

我希望为所有行做到这一点:

column2/(column3*column4)

然后在新文件中打印输出。

我写了一个bash脚本来做它,但它有点慢,所以我正在寻找一个更有效的解决方案(也许与awk?)。

这是我的代码

while read line
do
        out0=$(awk '{print $1}' <<< $line)
        out1=$(awk '{print $2}' <<< $line)
        out2=$(awk '{print $3}' <<< $line)
        out3=$(awk '{print $4}' <<< $line)
        out4=`echo "scale=5; ($out1 / ($out2 * $out3))"|bc -l`
        echo "$out0;$out4"
done < $file

是的, awk在这里非常有效:

awk '{ print $2/($3 * $4) }' file > newfile

如果你用read分割行(如@Cyrus建议,但没有div

while read -r column1 column2 column3 column4
do
    echo "bc: $column1;$( echo "scale=5; ($column2 / ($column3 * $column4))"|bc )"
done < $file

它会快一点。 在我的机器上6秒/ 1000行与1.7秒/ 1000行。

结合使用sedbcpaste

{
  echo "scale=5;"
  sed -re 's/(.*) ([0-9]+) ([0-9]+) ([0-9]+)/\2 \/ ( \3 * \4 )/' $file
} | bc > $$.tmp
cut -d ' ' -f 1 $file | paste - $$.tmp

它已经在1.1秒/ 100000行中完成。 这是〜150的因素,并解释了为什么while循环有一个坏名声。

使用ksh93,它允许浮点运算,你得到相似的数字。

typeset -F5 column2 column3 column4
while read -r column1 column2 column3 column4
do
    printf "printf %s;%.5f\n" "$column1 " "$(( column2 / (column3 * column4) ))"
done < $file

0.9秒/ 100,000行。 这表明,它不是循环本身,而是在循环中使用外部命令bc

是的,awk仍然快~8倍,1.4秒/ 1,000,000行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM