找到恰好两次出现的字符?

时间:2012-10-02 04:17:04

标签: bash unix

例如,假设字符串“test this”已插入我的应用程序 - 我只想要s

我正在考虑使用grep通配符,但我从未真正使用它们。

3 个答案:

答案 0 :(得分:2)

你可以写一个剧本。

  1. 对每个角色进行迭代。
  2. 为每个角色增加一个计数器。
  3. 最后,检查您的计数器是否等于2

答案 1 :(得分:1)

这是alex'的纯粹bash实现。建议做史蒂夫在awk中所做的事情:

#!/bin/bash

# your string
string="test this"


# First, make a character array out of it
for ((i=0; i<"${#string}"; i++)); do  # (quotes just for SO higlighting)
    chars[$i]="${string:$i:1}"        # (could be space, so quoted)
done

# associative array will keep track of the count for each character
declare -A counts

# loop through each character and keep track of its count
for ((i=0; i<"${#chars[@]}"; i++)); do # (quotes just for SO higlighting)

    key="${chars[$i]}"              # current character 
                                    # (could be space, so quoted)

    if [ -z counts["$key"] ]; then  # if it doesn't exist yet in counts, 
        counts["$key"]=0;           # initialize it to 0
    else
        ((counts["$key"]++))        # if it exists, increment it
    fi

done

# loop through each key/value and print all with count 2
for key in "${!counts[@]}"; do
    if [ ${counts["$key"]} -eq 2 ]; then
        echo "$key"
    fi
done 

请注意,它使用了一个在Bash 4.0中引入的关联数组,所以这只适用于那个或更新的。

答案 2 :(得分:0)

使用GNU awk的一种方式:

echo "$string" | awk -F '' '{ for (i=1; i<=NF; i++) array[$i]++; for (j in array) if (array[j]==2) print j }'