使用grep命令查找带有点的变量内容

4

我发现有很多类似于我问题的提问,但还是没有找到适合我的答案。 我需要使用grep命令匹配一个变量加上一个点号的内容,但在变量后面添加转义字符“.”后,它并不能正确运行。例如:

item.
newitem.

我的变量内容是item.,我想要精确匹配这个单词,因此我必须使用-w选项而不是-F选项,但是我用以下命令却得不到正确的输出:

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

你有什么建议吗?

嗨,我需要更正我的情况。我的文件包含一些FQDN并且出于某些原因我必须查找带有点号的hostname.。不幸的是,grep -wF无法运行:

hostname1.domain.com
hostname2.domain.com

和命令
cat file | grep -wF hostname1.

没有任何输出。我必须找到另一个解决方案,我不确定grep能否帮助。


从您的原始输入来看,似乎只想匹配单词。这就是为什么choroba的正确答案使用了-w选项。只需删除它,它就可以适用于您的更新输入:grep -F hostname1. file - PesaThe
很高兴它对你有用 :) 请考虑接受choroba的答案 - PesaThe
你是对的。我很抱歉造成混淆。-w-F都没有运行,我不太明白为什么,但我用grep "^$hostname\."解决了问题。 - intore
你确定 choroba 的回答 不起作用吗?它应该可以在不使用 -w 选项的情况下工作 :) - PesaThe
6个回答

8
如果$variable包含item.,则你正在搜索item.\.,这不是你想要的。实际上,你想要使用-F,它会将模式视为字面值而非正则表达式。
var=item.
echo $'item.\nnewitem.' | grep -F "$var"

谢谢,但我需要纠正我的情况:内容文件中有一些带有某些fqdn的行,因此我需要使用“hostname.”进行grep,但grep -wF无法运行。 - intore
@intore,不清楚哪里出了问题。但您可以更改示例输入和确切的grep命令,以显示失败的情况... - Sundeep

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

应该像\<一样工作,确保前一个字符不是单词组成部分。


0

您正在对变量进行取消引用并在其后附加\。,这将导致调用

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

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


0

尝试:

grep "\b$word\."

  1. \b:单词边界
  2. \.:点本身就是一个单词边界

0

以下 awk 解决方案可能会对您有所帮助。

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

0

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

rexp='^hostname1\.'

grep "$rexp" file.txt

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接