How do I add numbers from two txt files with Bash?
Along the paste
lines, but doing the math with bc
:
$ paste -d+ file1 file2 | bc
7
9
11
13
15
The intermediate result (before bc
):
$ paste -d+ file1 file2
1+6
2+7
3+8
4+9
5+10
For a more bash-centric solution, and assuming that file2 has at least as many lines as file1:
mapfile -t file1 < file1
mapfile -t file2 < file2
for((i=0; i < ${#file1[@]}; i++))
do
printf '%d\n' $((file1[i] + file2[i]))
done
... and for non-whole numbers, combine the ideas:
mapfile -t file1 < file1
mapfile -t file2 < file2
for((i=0; i < ${#file1[@]}; i++))
do
printf '%d + %d\n' "${file1[0]}" "${file2[0]}" | bc
done
This is basic task many tools can solve; paste
+ awk
combo seems exceptionally handy:
$ paste file1 file2 | awk '{$0=$1+$2}1'
7
9
11
13
15
an awk
-only solution
awk '(getline a <"file2") <= 0 {exit}; {print $0 + a}' file1