bash 计算两个文件中数字的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2401997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate difference of numbers in two files
提问by vehomzzz
Say I have two files where there is one number per line
假设我有两个文件,每行有一个数字
File 1 file 2
0.12 0.11
0.121 0.454
.... ....
I want to create file or output difference between each number on to the screen, so that result looks like
我想在屏幕上的每个数字之间创建文件或输出差异,以便结果看起来像
0.0099
-0.333
......
You can use bash/awk/sed
你可以使用 bash/awk/sed
回答by Damodharan R
Following shows how to get file1 - file2
下面显示了如何获取文件 1 - 文件 2
$ cat file1
0.12
0.43
-0.333
$ cat file2
-0.1
-0.2
0.2
$ paste file1 file2 | awk '{print - }'
0.22
0.63
-0.533
回答by ghostdog74
awk
awk
awk '{getline t<"file1"; print exec 4<"file1"
while read -r line
do
read -r s <&4
echo "${line}-${s}" | bc
done <"file2"
exec >&4-
-t}' file2 #file2-file1
Explanation: getline t <"file1"gets a line from file1and puts its value to variable t. $0is the current record of file2that awk is processing. the rest is just subtraction and printing the result out.
说明:getline t <"file1"从file1变量中获取一行并将其值放入变量t。$0是该file2awk 正在处理的当前记录。剩下的就是减法和打印结果。
Bash
重击
# cat f1
0.12
0.121
# cat f2
0.11
0.454
# pr -m -t -s\ f1 f2 | gawk '{print -}'
0.01
-0.333
回答by DVK
paste file1 file2 | while read a b ; do
echo "$a - $b" | bc
done
回答by Chen Levy
Bash:
重击:
paste -d - num1 num2 | bc
回答by Paused until further notice.
yes '-' | head -n $(wc -l < num1) | paste -d ' ' num1 - num2 | bc
Edit:
编辑:
This version properly handles negative numbers:
此版本正确处理负数:
##代码##
