shell数值操作(四则运算,浮点数,科学计数法)---awk,bc

1

两个文件对应行的数值进行数值计算 

#!/bin/bash
#use awk to handle Scientific notation
#use bc to handle float

for loop in  1
do
     d=`ls ./performance.v1/${loop}thread/*.ori `

      for f in $d
      do
         echo $f
         line=`cat $f | wc -l`

        rm ${f}-minus
#       for ((i=1;i<=$line;i++))
           for i in `seq $line`

         do
          file1=` awk '{ if(NR=='"$i"') print $2}' ${f} `

#NR代表行号
          echo $file1
     file2=` awk '{ if(NR=='"$i"') print $2}' ${f/v1/v2/} `
#      字符串替换   ${f/v1/v2/} `

echo $file2

if echo $file1 | grep "E"
then
result=`echo "$file1 $file2" | awk '{print "%f",$1-$2}'`

# awk可以对科学计数法进行计算
echo $result>>${f}-minus
echo "result"

else

         result=` echo "$file1 - $file2" | /home/xuanji/bc-1.06/bc/bc`

#bc可以处理浮点数
          echo $result
          echo "result"
        echo $result >>${f}-minus

fi
          done
      done
done




2  参考代码:

shell脚本,一行一行比较两个文本文件。 shell脚本,对一行一行读取文本文件得到的那一行数据进行字符串

2012-11-12 15:58 提问者: ShiJingCai075 | 浏览次数:376次
以逗号分割。
比如文本文件的数据:
group1,table1,name,1
group2,table1,name,2
我来帮他解答
满意回答
2012-11-12 18:28
没明白你的意思,就写了一个判断两个文件对应行是不是相同。在线的话就追问我。
line=`cat file1|wc -l`
for ((i=1;i<=$line;i++));do
  file1=`awk 'NR="'$i'"{print $0}'` file1
  file2=`awk 'NR="'$i'"{print $0}'` file2
  if [ $file1 == $file2 ];then
    echo line $i looks same!
  else
    echo line $i looks different!
  fi
done
追问
对读取的一行一行的文件内容以逗号分割,我现在已经做出来了,比如这种:
fileGroupId=`echo $line | awk -F ',' '{ print $1; }'`
columnName=`echo $line | awk -F ',' '{ print $7; }'
##然后比较。
if [[ $fileGroupId != $groupParam ]]; then
网址:http://zhidao.baidu.com/question/496930297.html

### 对科学计数法表示的数字进行四舍五入 对于给定的科学计数法表示的数字 `1.738029861448174E12`,可以将其转换为常规形式后再执行四舍五入操作。具体实现取决于所使用的编程环境。 #### Python 实现 Python 提供了内置函数来处理浮点数并支持指定精度下的四舍五入: ```python number = 1.738029861448174e12 rounded_number = round(number, ndigits=-int(math.floor(math.log10(abs(number)))) + desired_precision) print(f"原始值: {number}") print(f"四舍五入后的结果 ({desired_precision}位有效数字): {rounded_number:.{desired_precision}g}") ``` 在这个例子中,假设希望保留三位有效数字,则设置 `desired_precision=3`: ```python import math number = 1.738029861448174e12 desired_precision = 3 rounded_number = round(number, -int(math.floor(math.log10(abs(number)))) + desired_precision) print(f"原始值: {number}") print(f"四舍五入后的结果 ({desired_precision}位有效数字): {rounded_number:.{desired_precision}g}")[^1] ``` 上述代码会输出类似于下面的结果: ``` 原始值: 1.738029861448174e+12 四舍五入后的结果 (3位有效数字): 1.74e+12 ``` #### Shell 脚本实现 如果是在Shell环境中工作,可以通过调用外部工具如`awk`来进行此操作: ```bash echo "scale=3; ((1.738029861448174 * 10^12)/1)" | bc ``` 不过更推荐的方式是利用专门用于数值运算的语言特性或库函数完成这一任务,因为直接在命令行下做高精度计算可能会遇到一些局限性和误差问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值