在Unix中找到两个字符串中最长的公共子字符串的shell命令是什么? [英] What is a shell command to find the longest common substring of two strings in unix?

查看:147
本文介绍了在Unix中找到两个字符串中最长的公共子字符串的shell命令是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Unix中找到两个字符串中最长的公共子字符串的shell命令是什么? 如:foo'abcdefghi''abjklmdefnop' 打印:def

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

推荐答案

我不确定是否有单个命令可以为您完成这项工作,但以下bash脚本应该可以完成.

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

将以上内容另存为文件substr.sh 做chmod + x substr.sh

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

这篇关于在Unix中找到两个字符串中最长的公共子字符串的shell命令是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆