简体   繁体   English

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

[英]Linux terminal command line variable using in grep

I want to display the amount of words that have exactly 14, 15 and 16 unique letters. 我想显示恰好有14、15和16个唯一字母的单词数量。 I want to use a for loop. 我想使用一个for循环。 (It has to be a one liner.) (它必须是一个班轮。)

This is what I have so far: 这是我到目前为止的内容:
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

Result: 结果:

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

This means the loop works and when I run it like this: 这意味着循环有效,当我像这样运行时:

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"

The results are: 结果是:
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

This shows that I am doing something wrong with the variable ($i) inside the grep-command. 这表明我在grep-command中的变量($ i)做错了。 I don't know how I should do it or solve this problem. 我不知道该怎么办或解决这个问题。

Thanks in advance 提前致谢

It looks like you need to use single quotes instead of double quotes around the variable in your first regex: 看起来您需要在第一个正则表达式中的变量周围使用单引号而不是双引号:

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

Because your first regex was wrapped in single quotes, it was being used literally, without any variable expansion. 由于您的第一个正则表达式用单引号引起来,因此按原样使用它,没有任何变量扩展。 By putting the variable in single quotes, you're actually specifying two literal strings wrapped tightly around your actual variable (put another way, your variable isn't actually wrapped in any quotes at all). 通过将变量放在单引号中,您实际上是在指定两个紧紧围绕实际变量的文字字符串(换句话说,您的变量实际上根本没有用任何引号引起来)。


Edit: This is what I get on my system: 编辑:这是我在系统上得到的:

$ 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

Edit 2: This might demonstrate the issue more clearly: 编辑2:这可能更清楚地说明问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM