将输出通过管道传输到 echo 作为计算变量

问题描述 投票:0回答:1

我的目标是划分 2 个文本文件,每个文件包含一个整数, 但将答案限制为小数点后两位。

我成功做到了

paste total.txt count.txt | awk '{printf "%.2f\n", $1/$2}'

但是我看到了另一种使用方式

echo 'scale=2; <calculation here>' | bc -l

我不知道如何将数字从前一个管道传递到

echo
作为变量/参数,我尝试使用
xargs
但不知道如何引用它。

我试过这个:

paste -d/ total.txt count.txt | bc -l | xargs echo 'scale=2;' | bc -l

还有这个:
echo 'scale=2; $(paste -d/ total.txt count.txt)/1' | bc -l

我的目标是将输出通过管道传输到

echo
作为计算变量或在
echo
中使用命令,谢谢。

linux bash terminal pipe echo
1个回答
0
投票

我会做什么:

total.txt = 100    
count.txt = 3  
bc <<< "scale=2; $(paste -d '/' total.txt count.txt);"
33.33

echo "scale=2; $(paste -d '/' total.txt count.txt);" | bc -l
33.33

您的尝试:

echo 'scale=2; $(paste -d/ total.txt count.txt)/1' | bc -l

很接近,但使用单引号,可以防止 shell 展开

$(command substitution)

© www.soinside.com 2019 - 2024. All rights reserved.