string - 如何在 bash 中找到两个字符串之间的公共(public)字符?

标签 string bash shell

例如:

s1="my_foo"
s2="not_my_bar"

期望的结果是my_o。我如何在 bash 中执行此操作?

最佳答案

我下面的解决方案使用 fold 将字符串分成每行一个字符,使用 sort 对列表进行排序,使用 comm 比较两者strings 最后 tr 删除新行字符

comm -12 <(fold -w1 <<< $s1 | sort -u) <(fold -w1 <<< $s2 | sort -u) | tr -d '\n'

或者,这是一个纯 Bash 解决方案(它还保持字符的顺序)。它遍历第一个字符串并检查第二个字符串中是否存在每个字符。

s="temp_foo_bar"
t="temp_bar"
i=0
while [ $i -ne ${#s} ]
do
    c=${s:$i:1}
    if [[ $result != *$c* && $t == *$c* ]]
    then
      result=$result$c
    fi
    ((i++))
done
echo $result

打印:temp_bar

关于string - 如何在 bash 中找到两个字符串之间的公共(public)字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6941924/

相关文章:

python - 字典内的字符串格式?

c - 大小 8 valgrind 的无效写入

linux - 寻找匹配 `"时意外的 EOF '

bash - 使用bash输入c程序的stdin

c# - 由于字符串是不可变的,具有相同字符串值的变量是否指向同一个字符串对象?

ios - xcode-字符串执行错误

linux - 使用 Sed 或 Perl 替换 .bashrc 中的 PS1 变量

bash - 无法运行安装后脚本

android - 使用sed操作xml文件

linux - 在 Solaris OS 上使用主机名重命名文本文件