2013-11-21 47 views
-1
$> cat file1.txt 
15,20,8, 

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

文件中只有一行。我想比較兩個文件中以逗號分隔的數字,並將差異保存到舊值的旁邊。如何比較兩個文件中的數字並將差異保存到使用bash的文件之一中?

因此,使用file1.txt爲基礎,比較file2.txt後,我希望看到:

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

是否有可能?

+5

是的,這是可能的。到目前爲止你做了什麼? –

+0

你如何比較這兩個文件?試着更加明確。 – perror

回答

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 
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 
相關問題