如何在bash中找到两个字符串之间的常用字符?

时间:2011-08-04 13:04:46

标签: string bash shell

例如:

s1="my_foo"
s2="not_my_bar"

期望的结果是my_o。我怎么在bash中这样做?

7 个答案:

答案 0 :(得分:9)

我的解决方案使用fold将字符串分成每行一个字符,sort对列表进行排序,comm比较两个字符串,最后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

答案 1 :(得分:2)

假设字符串不包含嵌入的换行符:

s1='my_foo' s2='my_bar'
intersect=$(
  comm -12 <(
    fold -w1 <<< "$s1" |
      sort -u
      ) <(
        fold -w1 <<< "$s2" |
          sort -u
          ) |
            tr -d \\n
            )

printf '%s\n' "$intersect" 

还有一个:

tr -dc "$s2" <<< "$s1"

答案 2 :(得分:2)

迟到了,我刚刚找到这个页面:

echo "$str2" |
  awk 'BEGIN{FS=""}
  { n=0; while(n<=NF) {
   if ($n == substr(test,n,1)) { if(!found[$n]) printf("%c",$n); found[$n]=1;} n++;
  } print ""}' test="$str1"

和另一个,这个构建一个匹配的正则表达式(注意:不适用于特殊字符,但这并不难以与其他sed一起修复)

echo "$str1" |
  grep -E -o ^`echo -n "$str2" | sed 's/\(.\)/(|\1/g'; echo "$str2" | sed 's/./)/g'`

答案 3 :(得分:1)

应该是便携式解决方案:

s1="my_foo"  
s2="my_bar"
while [ -n "$s1" -a -n "$s2" ]
do
    if [ "${s1:0:1}" = "${s2:0:1}" ]
    then
        printf %s "${s1:0:1}"
    else
        break
    fi
    s1="${s1:1:${#s1}}"
    s2="${s2:1:${#s2}}"
done

答案 4 :(得分:1)

comm=""
for ((i=0;i<${#s1};i++))
do 
  if test ${s1:$i:1} = ${s2:$i:1}
  then 
    comm=${comm}${s1:$i:1}
  fi
done

答案 5 :(得分:1)

使用单个sed执行的解决方案:

echo -e "$s1\n$s2" | sed -e 'N;s/^/\n/;:begin;s/\n\(.\)\(.*\)\n\(.*\)\1\(.*\)/\1\n\2\n\3\4/;t begin;s/\n.\(.*\)\n\(.*\)/\n\1\n\2/;t begin;s/\n\n.*//'

作为所有神秘的sed脚本,它需要以echo -e "$s1\n$s2" | sed -f script运行的sed脚本文件的形式进行说明:

# Read the next line so s1 and s2 are in the pattern space only separated by a \n.
N
# Put a \n at the beginning of the pattern space.
s/^/\n/
# During the script execution, the pattern space will contain <result so far>\n<what left of s1>\n<what left of s2>.
:begin
# If the 1st char of s1 is found in s2, remove it from s1 and s2, append it to the result and do this again until it fails.
s/\n\(.\)\(.*\)\n\(.*\)\1\(.*\)/\1\n\2\n\3\4/
t begin
# When previous substitution fails, remove 1st char of s1 and try again to find 1st char of S1 in s2.
s/\n.\(.*\)\n\(.*\)/\n\1\n\2/
t begin
# When previous substitution fails, s1 is empty so remove the \n and what is left of s2.
s/\n\n.*//

如果要删除重复项,请在脚本末尾添加以下内容:

:end;s/\(.\)\(.*\)\1/\1\2/;t end

编辑:我意识到dogbane的纯shell解决方案具有相同的算法,可能效率更高。

答案 6 :(得分:0)

因为每个人都喜欢充满标点符号的perl单行:

perl -e '$a{$_}++ for split "",shift; $b{$_}++ for split "",shift; for (sort keys %a){print if defined $b{$_}}' my_foo not_my_bar

从输入字符串中创建哈希%a%b 打印两个字符串共有的任何字符。

输出:

_moy