shell - 两个字符串中包含的字符 - 已编辑

标签 shell unix dash-shell

我想比较两个字符串变量并打印两者相同的字符。我不太确定如何执行此操作,我正在考虑使用 commdiff 但我不太确定仅打印匹配字符的正确参数。他们还说他们接收文件,这些是字符串。有人可以帮忙吗?

输入:

a=$(echo "abghrsy")
b=$(echo "cgmnorstuvz")

输出:

"grs"

最佳答案

您不需要做那么多工作来分配 $a$b shell 变量,您只需...

a=abghrsy
b=cdgmrstuvz

现在,有一个经典的计算机科学问题,称为 longest common subsequence1和你的很相似。

但是,如果您只想要通用字符,有一种方法可以让 Ruby 完成这项工作...

$ ruby -e "puts ('$a'.chars.to_a & '$b'.chars.to_a).join"

1。不要与不同的 longest common substring problem. 混淆

关于shell - 两个字符串中包含的字符 - 已编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15846978/

相关文章:

bash - 无需 curl 或 bash 即可连接到网站

bash - 为什么带有 "#!/bin/sh"shebang 的脚本可以使用仅限 bash 的功能?

shell - 在unix shell脚本中从字符串变量执行命令

java - 从shell脚本运行java文件

bash - 相当于 dash shell 中的 pipefail

bash,破折号和字符串比较

linux - 增加一个环境变量

shell - nohup VERBOSE=1 perl script.pl

unix - 查找带有通配符或类似 "like"的目录名称

linux - linux shell脚本中for循环的语法