bash中两个字符串的最长公用前缀

前端之家收集整理的这篇文章主要介绍了bash中两个字符串的最长公用前缀前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个字符串。为了这个例子,它们是这样设置的:
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”,它们将不会重叠,因为检查从开头开始,而在字符串1的开始处为“a”。

在sed中,假设字符串不包含任何换行符:
string1="test toast"
string2="test test"
printf "%s\n%s\n" "$string1" "$string2" | sed -e 'N;s/^\(.*\).*\n\1.*$/\1/'
原文链接:https://www.f2er.com/bash/388114.html

猜你在找的Bash相关文章