Calculate the similarity percentage between two strings based on edit distance.
Code
Algorithmsdeclare -A dp
m=${#a}; n=${#b}
for ((i=0; i<=m; i++)); do dp[$i,0]=$i; done
for ((j=0; j<=n; j++)); do dp[0,$j]=$j; done
for ((i=1; i<=m; i++)); do
for ((j=1; j<=n; j++)); do
[[ "${a:i-1:1}" == "${b:j-1:1}" ]] && cost=0 || cost=1
del=$((dp[$((i-1)),$j] + 1))
ins=$((dp[$i,$((j-1))] + 1))
sub=$((dp[$((i-1)),$((j-1))] + cost))
min=$del; ((ins < min)) && min=$ins; ((sub < min)) && min=$sub
dp[$i,$j]=$min
done
done
max=$m; ((n > max)) && max=$n
echo $(( (max - dp[$m,$n]) * 100 / max ))Parameters
First string
Second string
Server
More Bash Snippets
Capitalize First Letter
Capitalize the first letter of a string while keeping the rest unchanged.
Capitalize Words
Capitalize the first letter of each word in a string (title case).
Center String
Center a string within a given width by padding with spaces.
Check if Palindrome
Check if a string is a palindrome by comparing characters from both ends.
Compare Strings (Case Insensitive)
Compare two strings ignoring case differences.
Convert to camelCase
Convert a string to camelCase format with lowercase first letter.