【问题标题】:Linux terminal command line variable using in grep在 grep 中使用 Linux 终端命令行变量
【发布时间】:2017-08-09 16:21:40
【问题描述】:

我想显示正好有 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 命令中的变量 ($i) 做错了。我不知道该怎么做或解决这个问题。

提前致谢

【问题讨论】:

  • 双引号中有双引号
  • 双引号中的双引号实际上是包裹在$()子shell中的,所以不会造成问题。

标签: linux variables terminal grep


【解决方案1】:

看起来您需要在第一个正则表达式中的变量周围使用单引号而不是双引号:

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}$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 2014-07-03
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多