2015-12-15 40 views
0

匹配我有這樣如何與分隔符全串在bash

"ABCD EFGH IJKL MNOP" 

一個字符串,我得到用戶的輸入,以配合每個子作爲一個整體,而不是部分的。 我該怎麼做?

這是我在做什麼目前

printf "\n Enter user input:" 

read userinput 

INPUT=$userinput 

if echo "ABCD EFGH IJKL MNOP" | grep -q "$INPUT"; then 
    echo "Matching..."; 
else 

    echo "Invalid entry "; 
fi 

與上面的代碼是它會匹配"ABC"的部分串的問題,

"GH「等等,我不想。我只需要用戶輸入與由分隔符隔開整個子比較。

回答

1

使用-wgrep

0123匹配整個單詞
echo "ABCD EFGH IJKL MNOP" | grep -w "$INPUT"; 

>>> INPUT=ABC 
>>> echo "ABCD EFGH IJKL MNOP" | grep -w "$INPUT"; 
>>> 
>>> INPUT=ABCD 
>>> echo "ABCD EFGH IJKL MNOP" | grep -w "$INPUT"; 
ABCD EFGH IJKL MNOP 
1

的grep -w

-w, --word-regexp 
      Select only those lines containing matches that form whole 
      words. The test is that the matching substring must either be 
      at the beginning of the line, or preceded by a non-word 
      constituent character. Similarly, it must be either at the end 
      of the line or followed by a non-word constituent character. 
      Word-constituent characters are letters, digits, and the 
      underscore. 

類似的鏈接:grep -w with only space as delimiter

相關問題