2017-08-09 65 views
0

我想要显示正好具有14,15和16个唯一字母的字的数量。我想要使​​用for循环。 (它必须是一个衬垫。)在grep中使用的Linux终端命令行变量

这是我到目前为止有:
for i in {14..16}; do echo "There are $(cat /usr/share/dict/dutch | grep -P '^.{"$i"}$' | grep -vP -c '(.).*\1') words with exactly $i unique letters"; done

结果:

There are 0 words with exactly 14 unique letters
There are 0 words with exactly 15 unique letters
There are 0 words with exactly 16 unique letters

这意味着环作品,当我这样运行它:

echo "There are $(cat /usr/share/dict/dutch | grep -P '^.{14}$' | grep -vP -c '(.).*\1') words with exactly 14 unique letters" && echo "There are $(cat /usr/share/dict/dutch | grep -P '^.{15}$' | grep -vP -c '(.).*\1') words with exactly 15 unique letters" && echo "There are $(cat /usr/share/dict/dutch | grep -P '^.{16}$' | grep -vP -c '(.).*\1') words with exactly 16 unique letters"

的结果是:
There are 13 words with exactly 14 unique letters
There are 2 words with exactly 15 unique letters
There are 0 words with exactly 16 unique letters

这表明,我做错了什么用的grep命令里面的变量($ I)。我不知道我该怎么做或解决这个问题。

在此先感谢

+0

你得双双引号引号 – JNevill

+0

双引号中的双引号实际上包裹在$()子shell中,因此它们不会导致问题。 –

回答

0

它看起来像你需要使用单引号,而不是周围的可变双引号在你的第一个正则表达式:

for i in {14..16}; do 
    echo "there are $(cat /usr/share/dict/dutch | grep -P '^.{'$i'}$' | grep -vP -c '(.).*\1') words with exactly $i unique letters"; 
done 

因为你的第一个正则表达式被包裹在单引号,它被直接使用,没有任何可变的扩展。通过将变量放在单引号中,您实际上指定了两个紧紧围绕实际变量的文字字符串(换句话说,您的变量实际上并未包含在任何引号中)。


编辑:这是我得到我的系统上:

$ for i in {14..16}; do echo "there are $(cat /usr/share/dict/dutch | grep -P '^.{'$i'}$' | grep -vP -c '(.).*\1') words with exactly $i unique letters"; done 
there are 13 words with exactly 14 unique letters 
there are 2 words with exactly 15 unique letters 
there are 0 words with exactly 16 unique letters 

编辑2:这可能表现出更清晰的问题:

$ i=12 
$ echo '^.{"$i"}$' 
^.{"$i"}$ 
$ echo '^.{'$i'}$' 
^.{12}$