$> cat file1.txt
15,20,8,
$> cat file2.txt
10,20,30,
文件中只有一行。我想比较两个文件中逗号分隔的数字,并将差异保存在旧值旁边。
因此,在使用file1.txt
作为基础后,与file2.txt
进行比较后,我希望看到:
15(+5),20,8(-22),
有可能吗?
答案 0 :(得分:0)
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