gpt4 book ai didi

bash - bash中两个字符串的最长公共(public)前缀

转载 作者:行者123 更新时间:2023-11-29 08:42:26 26 4
gpt4 key购买 nike

我有两个字符串。为了示例的缘故,它们设置如下:

string1="test toast"
string2="test test"

我想要的是找到从字符串开头开始的重叠部分。对于重叠,我指的是上面示例中的字符串“test t”。

# So I look for the command 
command "$string1" "$string2"
# that outputs:
"test t"

如果字符串是 string1="atest toast"; string2="test test" 它们不会重叠,因为检查是从头开始的,并且是 string1 开头的“a”。

最佳答案

在 sed 中,假设字符串不包含任何换行符:

string1="test toast"
string2="test test"
printf "%s\n%s\n" "$string1" "$string2" | sed -e 'N;s/^\(.*\).*\n\1.*$/\1/'

关于bash - bash中两个字符串的最长公共(public)前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6973088/

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