我正在尝试编写一个 bash 命令来查找一个字符串是否包含一个又一个重复的相同字母数字字符。
例如:
input: aaa, abc, aba, abc111;
output: aaa, abc111.
“aba”不被视为一个接一个地重复相同的字母数字字符。“11”、“111”、“aa”、“aaaaaaaaa”等被视为“重复”。不用担心输入。假设 is 已在其他地方定义为字符串。
说:INPUT="aa"
我正在尝试编写一个 bash 命令来查找一个字符串是否包含一个又一个重复的相同字母数字字符。
例如:
input: aaa, abc, aba, abc111;
output: aaa, abc111.
“aba”不被视为一个接一个地重复相同的字母数字字符。“11”、“111”、“aa”、“aaaaaaaaa”等被视为“重复”。不用担心输入。假设 is 已在其他地方定义为字符串。
说:INPUT="aa"
使用tr
可以提供帮助。(使用在-s
定义的集合中挤压重复的选项。)
例子:
$ a="abcdef"
$ [ $(echo ${a} | tr -s '[:alnum:]') == "${a}" ] && echo "No repeating characters" || echo "Repeating characters present"
No repeating characters
$ a="abc1111"
$ [ $(echo ${a} | tr -s '[:alnum:]') == "${a}" ] && echo "No repeating characters" || echo "Repeating characters present"
Repeating characters present
$ a="abc123"
$ [ $(echo ${a} | tr -s '[:alnum:]') == "${a}" ] && echo "No repeating characters" || echo "Repeating characters present"
No repeating characters
$ a="aaa123"
$ [ $(echo ${a} | tr -s '[:alnum:]') == "${a}" ] && echo "No repeating characters" || echo "Repeating characters present"
Repeating characters present
$ a="abacdc"
$ [ $(echo ${a} | tr -s '[:alnum:]') == "${a}" ] && echo "No repeating characters" || echo "Repeating characters present"
No repeating characters
事实上,正则表达式匹配您的目标:
'([0-9a-zA-Z])\1'
如果你想打印这些词,试试这个:
grep -oE '\b\w*([0-9a-zA-Z])\1\w*\b'
用你的例子测试:
kent$ echo "aaa, abc, aba, abc111"|grep -oE '\b\w*([0-9a-zA-Z])\1\w*\b'
aaa
abc111
如果数组中有一组单词,则此代码将起作用:
#!/bin/bash
WORDS=(aaa abc aba abc111)
for W in "${WORDS[@]}"; do
P=''
for (( I = 0; I < ${#W}; ++I )); do
C=${W:I:1}
[[ $C == "$P" ]] && {
echo "$W"
break
}
P=$C
done
done
输出:
aaa
abc111