2017-08-09 64 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}$