views:

130

answers:

5

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

+4  A: 

awk

awk '{getline t<"file1"; print $0-t}' file2  #file2-file1

Explanation: getline t <"file1" gets a line from file1 and puts its value to variable t. $0 is the current record of file2 that awk is processing. the rest is just subtraction and printing the result out.

Bash

exec 4<"file1"
while read -r line
do
    read -r s <&4
    echo "${line}-${s}" | bc
done <"file2"
exec >&4-
ghostdog74
Nice and it works! Would you please explain how it does it?
vehomzzz
A: 
# cat f1
0.12
0.121
# cat f2
0.11     
0.454

# pr -m -t -s\  f1 f2 | gawk '{print $1-$2}'
0.01
-0.333
DVK
+6  A: 

Following shows how to get file1 - file2

$ cat file1
0.12
0.43
-0.333

$ cat file2
-0.1
-0.2
0.2

$ paste file1 file2 | awk '{print $1 - $2}'
0.22
0.63
-0.533
Damodharan R
Absolutely Beautiful!
vehomzzz
what if there is a blank line in one of the file
Vijay Sarathi
if there is a blank line it will made as zero in subtraction.$ cat file10.120.43-0.33310$ cat file2-0.1-0.20.2$ paste file1 file2 | awk '{print $1 - $2}'0.220.63-0.53310
Damodharan R
A: 

Bash:

paste file1 file2 | while read a b ; do 
  echo "$a - $b" | bc
done
Chen Levy
Doesn't work with negative numbers ?
Paul R
This solution is too `fork`-heavy for large files (it doesn't need to be.)
vladr
A: 
paste -d - num1 num2 | bc

Edit:

This version properly handles negative numbers:

yes '-' | head -n $(wc -l < num1) | paste -d ' ' num1 - num2 | bc
Dennis Williamson
your 2nd version has a lot of overheads.
ghostdog74
@ghostdog74: A little overhead, maybe, but how does it have a lot?
Dennis Williamson