grep表示带点的可变内容

时间:2018-01-17 10:09:06

标签: bash grep

我发现了许多关于我的问题的类似问题,但我仍然找不到适合我的问题。 我需要grep一个变量加上一个点的内容,但它不会在变量之后运行转义点。例如: 文件内容是

item.
newitem.

我的变量内容是item.,我想要grep查找确切的单词,因此我必须使用-w而不是-F但是使用命令我无法获得正确的输出:

cat file | grep -w "$variable\."

你有建议吗?

嗨,我必须纠正我的情况。我的文件包含一些FQDN,由于某些原因,我必须用点查找hostname.。 不幸的是,grep -wF没有运行: 我的档案是

hostname1.domain.com
hostname2.domain.com

和命令

cat file | grep -wF hostname1.

不显示任何输出。我必须找到另一种解决方案,而且我不确定grep是否有帮助。

6 个答案:

答案 0 :(得分:5)

如果$ variable包含item.,那么您正在搜索item.\.,这不是您想要的。实际上,您希望-F按字面解释模式,而不是正则表达式。

var=item.
echo $'item.\nnewitem.' | grep -F "$var"

答案 1 :(得分:0)

您正在取消引用变量并向其附加\.,这会导致调用

cat file | grep -w "item.\."

由于grep接受文件作为参数,因此应调用grep "item\." file

答案 2 :(得分:0)

尝试:

grep "\b$word\."
  1. \b:字边界
  2. \.:点本身是一个单词边界

答案 3 :(得分:0)

遵循awk解决方案可能对您有帮助。

awk -v var="item." '$0==var'   Input_file

答案 4 :(得分:0)

来自man grep

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

The Backslash Character and Special Expressions
   The  symbols  \<  and  \>  respectively  match  the  empty string at the beginning and end of a word.  The symbol \b matches the empty string at the edge of a word, and \B matches the empty string
   provided it's not at the edge of a word.  The symbol \w is a synonym for [[:alnum:]] and \W is a synonym for [^[:alnum:]].

由于最后一个字符为.,因此必须后跟非字[A-Za-z0-9_],但下一个字符为d

grep '\<hostname1\.'

应该有效\<确保前一个字符不是单词成分。

答案 5 :(得分:0)

您可以动态构建搜索模式,然后调用grep

rexp='^hostname1\.'

grep "$rexp" file.txt

单引号告诉bash不要解释变量中的特殊字符。双引号告诉bash允许用它的值替换$ rexp。表达式中的插入符号(^)告诉grep查找以“hostname1”开头的行。