Longest common prefix of two strings in bash

前端 未结 13 2315
一向
一向 2020-12-03 00:49

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

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

What I want is to find

13条回答
  •  隐瞒了意图╮
    2020-12-03 01:38

    Grep short variant (idea borrowed from sed one):

    $ echo -e "String1\nString2" | grep -zoP '^(.*)(?=.*?\n\1)'
    String
    

    Assumes string have no new line character. But easy may be tuned to use any delimiter.

    Update at 2016-10-24: On modern versions of grep you may receive complain grep: unescaped ^ or $ not supported with -Pz, just use \A instead of ^:

    $ echo -e "String1\nString2" | grep -zoP '\A(.*)(?=.*?\n\1)'
    String
    

提交回复
热议问题