Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a shell command to find the longest common substring of two strings in unix?

What is a shell command to find the longest common substring of two strings in unix? like: foo 'abcdefghi' 'abjklmdefnop' prints: def

like image 385
user1081596 Avatar asked Feb 21 '12 18:02

user1081596


People also ask

What is a time complexity for finding the longest substring that is common in string?

To check if a substring is present in a string of a length of n, the time complexity for such operation is found to be O (n). The time complexity for finding the longest substring that is repeated in a string is Ɵ (n).


1 Answers

I am not sure if there is a single command that does the job for you but the following bash script should do it.

#!/bin/bash

word1="$1"
word2="$2"
if [ ${#word1} -lt ${#word2} ]
then
        word1="$2"
        word2="$1"
fi
for ((i=${#word2}; i>0; i--)); do
        for ((j=0; j<=${#word2}-i; j++)); do
                if [[ $word1 =~ ${word2:j:i} ]]
                then
                        echo ${word2:j:i}
                        exit
                fi
        done
done

save the above as a file substr.sh do chmod +x substr.sh

pranithk @ ~
09:24:32 :) $ ./substr.sh 'abcdefghi' 'abcdeghi'
abcde

pranithk @ ~
09:24:33 :) $ ./substr.sh 'abcdefghi' 'abjklmdefnop'
def
like image 118
pranithk Avatar answered Oct 03 '22 07:10

pranithk