【问题标题】:How to grep while excluding some words?如何在排除某些单词的同时进行grep?
【发布时间】:2018-11-21 06:29:12
【问题描述】:

我想 grep 单词“force”,但列出的大部分输出来自命令 -force

当我执行 grep -v "-force" filename 时,它说 grep : orce 很可能是因为 -f 命令。

我只想使用 grep 从文件中查找 force 信号。怎么样?

【问题讨论】:

  • 你想说你想grep“force”而不是“-force”吗?

标签: linux unix command


【解决方案1】:

使用grep -v -- "-force" - 双重- 表示预期没有更多选项。

【讨论】:

  • 完整答案是grep -v -- "-force" | grep force
【解决方案2】:

如果你想从文件中 grep 特定的单词,那么我们可以使用 cat 命令

 # cat 文件名.txt | grep 强制

其他基本Commands

【讨论】:

  • cat 在这里是多余的。只需 grep 文件。谷歌“无用的猫”:)
【解决方案3】:

这一行可能更简单:

grep '[^-]force' tmp

它说:grep "force",但前提是它没有前缀 -,使用 [^]。查看一些简单的正则表达式示例here

【讨论】:

    【解决方案4】:

    使用 [-] 删除特殊意义。看看这个:

    > cat rand_file.txt
    1. list items of random text
    2. -force
    3. look similar as the first batch
    4. force
    5. some random text
    > grep -v "-force" rand_file.txt  
    grep: orce: No such file or directory
    > grep -v "[-]force" rand_file.txt | grep force
    4. force
    > 
    

    【讨论】:

    • 我认为您需要在最后一个命令的末尾添加| grep force,因为只有第 4 行是可取的(强制信号)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2020-01-21
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多