【问题标题】:grep obtains pattern from a file but printing not only the whole match wordgrep 从文件中获取模式,但不仅打印整个匹配词
【发布时间】:2020-12-06 05:51:11
【问题描述】:

我有 file.txt 来提取包含 check.txt 文件中列出的确切单词的行。

# file.txt
CA1C 2637 green
CA1C-S1 2561 green
CA1C-S2 2371 green

# check.txt
CA1C

我试过了

grep -wFf check.txt file.txt

但我没有得到想要的输出,即所有三行都被打印出来了。

相反,我只想得到第一行,

CA1C 2637 green

我搜索并发现这个post 是相关的,当只进行一个单词匹配时很容易做到这一点。但是如何改进我的代码让 grep 从 check.txt 文件中获取模式并只打印整个单词匹配的行?

非常感谢!

【问题讨论】:

    标签: linux grep


    【解决方案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.
    

    在您的情况下,所有三行都以“CA1C-”开头,满足在行首,后跟非单词组成字符(连字符)的条件。

    我会通过循环来执行此操作,从 check.txt 中手动读取行:

    cat check.txt | while read line; do grep "^$line " file.txt; done
    CA1C 2637 green
    

    此循环从 check.txt 中读取行,并在 file.txt 的行首搜索每一行,后面有空格

    可能有更好的方法来做到这一点,但我无法让 -f 真正考虑输入文件行尾的空格。

    【讨论】: