在grep中使用的Linux终端命令行变量

时间:2017-08-09 16:21:41

标签: linux variables terminal grep

我想显示具有14,15和16个唯一字母的单词数量。我想使用for循环。 (它必须是一个班轮。)

这是我到目前为止: 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-command中对变量($ i)做错了。我不知道应该怎么做或解决这个问题。

提前致谢

1 个答案:

答案 0 :(得分: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}$