我有一个像这样的字符串
"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
“等我不想要的。我只需要用户输入来与分隔符分隔的整个子串进行比较。
答案 0 :(得分:1)
使用-w
匹配grep
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 :(得分: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.