如何在bash中将整个子字符串与分隔符匹配

时间:2015-12-15 06:01:37

标签: grep

我有一个像这样的字符串

"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“等我不想要的。我只需要用户输入来与分隔符分隔的整个子串进行比较。

2 个答案:

答案 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.

类似链接:grep -w with only space as delimiter