gpt4 book ai didi

linux - 什么是在 unix 中查找两个字符串的最长公共(public)子串的 shell 命令?

转载 作者:IT王子 更新时间:2023-10-29 00:53:51 25 4
gpt4 key购买 nike

在 unix 中查找两个字符串的最长公共(public)子串的 shell 命令是什么?像:foo 'abcdefghi' 'abjklmdefnop'打印:def

最佳答案

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

#!/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

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

pranithk @ ~
09:24:33 :) $ ./substr.sh 'abcdefghi' 'abjklmdefnop'
def

关于linux - 什么是在 unix 中查找两个字符串的最长公共(public)子串的 shell 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9383067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com