例如,假设字符串“test this”被插入到我的应用程序中——我只想要 s
我正在考虑 grep 通配符,但我从未真正使用过它们。
你可以写一个脚本。
2
。这是 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 中引入的关联数组,因此这只适用于该数组或更新版本。
一种使用方式GNU awk
:
echo "$string" | awk -F '' '{ for (i=1; i<=NF; i++) array[$i]++; for (j in array) if (array[j]==2) print j }'