-1

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

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

4

3 回答 3

2

你可以写一个脚本。

  1. 遍历每个字符。
  2. 每看到一个字符,就为每个字符增加一个计数器。
  3. 最后,检查你的计数器是否等于2
于 2012-10-02T04:23:14.433 回答
1

这是 alex 建议的纯 bash 实现,执行 steve 的操作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 中引入的关联数组,因此这只适用于该数组或更新版本。

于 2012-10-02T05:41:21.070 回答
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 }'
于 2012-10-02T04:41:25.653 回答