如何比较两个文件中的数字并使用bash将差异保存到一个文件中?

时间:2013-11-21 21:43:51

标签: bash

$> cat file1.txt
15,20,8,

$> cat file2.txt
10,20,30,

文件中只有一行。我想比较两个文件中逗号分隔的数字,并将差异保存在旧值旁边。

因此,在使用file1.txt作为基础后,与file2.txt进行比较后,我希望看到:

15(+5),20,8(-22),

有可能吗?

2 个答案:

答案 0 :(得分:0)

bash不是最好的问题,但仍然可行,有些事情是这样的:

AA="15,20,8"
BB="10,20,30"

IFS=","
declare -a A=($AA)
declare -a B=($BB)

for ((i=0; i<3; i++)); do
    if [ ${A[$i]} -eq ${B[$i]} ]; then
        echo -n ${A[$i]},
    else
        echo -n ${A[$i]}'('$((${A[$i]}-${B[$i]}))')',
    fi
done

答案 1 :(得分:0)

#!/bin/bash
#
# progname: diffcalc
# syntax:   diffcalc file1.txt file2.txt
#
# last element in file1.txt must always be a comma

read LINE1 < "$1"
read LINE2 < "$2"

while [ "$LINE1" ]                          #while LINE1 is not empty
do
    DIFF=$(( ${LINE1%%,*} - ${LINE2%%,*} )) #diff between first elements
    [ $DIFF -gt 0 ] && OUT="(+$DIFF)"
    [ $DIFF -eq 0 ] && OUT=""
    [ $DIFF -lt 0 ] && OUT="($DIFF)"
    RESULT="$RESULT""${LINE1%%,*}""$OUT,"   # append element and (diff),
    LINE1=${LINE1#*,} ; LINE2=${LINE2#*,}   # cut the first elements
done

echo "$RESULT" >"$1"                        #write outcome to FILE1