如何找到在bash两个字符串之间共性? [英] How do I find common characters between two strings in bash?
本文介绍了如何找到在bash两个字符串之间共性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
s1="my_foo"
s2="not_my_bar"
所期望的结果将是 my_o
。我如何在bash这样做呢?
the desired result would be my_o
. How do I do this in bash?
推荐答案
我下面使用的解决方案折叠
打破串入每行一个字,排序
来对列表排序,通讯
来两个字符串最后 TR
比较删除新行字符
My solution below uses fold
to break the string into one character per line, sort
to sort the lists, comm
to compare the two strings and finally tr
to delete the new line characters
comm -12 <(fold -w1 <<< $s1 | sort -u) <(fold -w1 <<< $s2 | sort -u) | tr -d '\n'
可替换地,这里是一个纯击溶液(其也保持的字符的顺序)。它遍历第一串并检查每一个字符是第二个字符串中present。
Alternatively, here is a pure Bash solution (which also maintains the order of the characters). It iterates over the first string and checks if each character is present in the second string.
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
这篇关于如何找到在bash两个字符串之间共性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文