Reputation: 113
I'm working on a script that compares two very similar decimal numbers and I want the script to print the portion that the two numbers share. For example, suppose I have the numbers 42.86579 and 42.84578. Since both numbers have the 42.8 portion in common, I would like the script to output 42.8. How should I go about implementing this?
Upvotes: 1
Views: 54
Reputation: 149971
You could search for the longest common prefix in two strings with sed
:
$ x=42.86579
$ y=42.84578
$ sed "s/\(.*\).* \1.*/\1/" <<< "$x $y"
42.8
Or slightly more concisely using GNU grep:
$ grep -Po '(.*).* \K\1' <<< "$x $y"
42.8
Upvotes: 3
Reputation: 88766
a=42.86579
b=42.84578
[[ ${a%.*} != ${b%.*} ]] && exit
for ((i=0;i<${#a};i++)); do
if [[ ${a:$i:1} == ${b:$i:1} ]]; then
echo -n ${a:$i:1}
else
break
fi
done
Output:
42.8
See: Bash's parameter expansion
Upvotes: 2