[英]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行。
結合使用sed
, bc
和paste
{
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.