在主脚本的命令行参数中有任何"?"字符时将运行的脚本。 我使用 i 来运行字母表,基本上将字母表中每个字母的每个"?"设置为$i。 我认为发生错误是因为字符数组末尾出现了一个无法与"?"进行比较的特殊字符,但我不知道如何处理。 我确实已经使用过ShellCheck了。
编辑:主脚本生成的文本文件包括命令行参数中提供的字母的所有排列(无重复),每个排列之间都有一个硬回车,我很确定硬返回字符是产生错误的原因。 下面是排列的示例.txt
at?
a?t
ta?
t?a
?at
?ta
这是略微编辑的脚本:
#reads the text file produced by another script into the array
readarray words < ./permute.txt
#runs through loop 26 times with i as a letter in the alphabet
for i in {a..z}; do
#runs through every word in the array provided by the text file
for j in "${words[@]}"; do
s=$j #sets $j to a variable to mess with
declare -a a
word=""
#splits string s into character array
while read -n 1 c; do a+=($c); done <<< "$s"
#checks array for "?", used as a blank tile and changes that character to $i
for k in "${a[@]}"; do if [ "$k" = "?" ]; then a[$k]=$i; fi; done
#puts the array back together into a string
for ((k=0; k<${#a}; k++)); do echo $word; word=$word${a[$k]}; done
valid=$(grep -w $word /usr/share/dict/words) #checks for word in dictionary
#statement that fixes bug where words with apostrophes end up in the output
if [ ${#valid} -eq ${#i} ]; then
echo "$valid"
fi
done
done
我明白 rigth 吗,你想用所有字符 a 替换 ?z,然后检查它们是否在字典中?我会尝试不手动数组工作,让 sed 为您工作(更换?
for i in {a..z}; do
for word in $(sed "s/?/$i/" permute.txt); do
grep -w $word /usr/share/dict/words
done
done
您甚至可以在变量中使用 bash 的内置替换:
for i in {a..z}; do
for word in $(< permute.txt); do
grep -w ${word/?/$i} /usr/share/dict/words
done
done
顺便说一句:我不明白最后一个if语句。由于$i是单个字符,$valid是整行,因此至少包含一个(在示例中)3个字符的单词,如果[ ${#valid} -eq ${#i} ]永远不会为真。