例如,假设字符串“test this”已插入我的应用程序 - 我只想要s
我正在考虑使用grep通配符,但我从未真正使用它们。
答案 0 :(得分:2)
你可以写一个剧本。
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 }'