在bash两个字符串的最长公共preFIX [英] Longest common prefix of two strings in bash

查看:130
本文介绍了在bash两个字符串的最长公共preFIX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串。为示例起见它们设置是这样的:

I have two strings. For the sake of the example they are set like this:

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

我要的是要找到起始于字符串的开始重叠。随着重叠我的意思是在我上面的例子中字符串t检验。

What I want is to find the overlap starting at the beginning of the strings. With overlap I mean the string "test t" in my above example.

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

如果字符串为字符串1 =ATEST敬酒字符串2 =试考他们将有没有重叠,因为检查开始形成的开始和一个在字符串1 的开始。

If the strings were string1="atest toast"; string2="test test" they would have no overlap since the check starts form the beginning and the "a" at the start of string1 .

推荐答案

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

In sed, assuming the strings don't contain any newline characters:

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

这篇关于在bash两个字符串的最长公共preFIX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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