How can I exclude one word with grep?

后端 未结 9 2431
孤独总比滥情好
孤独总比滥情好 2020-12-12 09:01

I need something like:

grep ^\"unwanted_word\"XXXXXXXX
相关标签:
9条回答
  • 2020-12-12 09:25

    I understood the question as "How do I match a word but exclude another", for which one solution is two greps in series: First grep finding the wanted "word1", second grep excluding "word2":

    grep "word1" | grep -v "word2"
    

    In my case: I need to differentiate between "plot" and "#plot" which grep's "word" option won't do ("#" not being a alphanumerical).

    Hope this helps.

    0 讨论(0)
  • 2020-12-12 09:26

    grep provides '-v' or '--invert-match' option to select non-matching lines.

    e.g.

    grep -v 'unwanted_pattern' file_name
    

    This will output all the lines from file file_name, which does not have 'unwanted_pattern'.

    If you are searching the pattern in multiple files inside a folder, you can use the recursive search option as follows

    grep -r 'wanted_pattern' * | grep -v 'unwanted_pattern'
    

    Here grep will try to list all the occurrences of 'wanted_pattern' in all the files from within currently directory and pass it to second grep to filter out the 'unwanted_pattern'. '|' - pipe will tell shell to connect the standard output of left program (grep -r 'wanted_pattern' *) to standard input of right program (grep -v 'unwanted_pattern').

    0 讨论(0)
  • 2020-12-12 09:27

    If your grep supports Perl regular expression with -P option you can do (if bash; if tcsh you'll need to escape the !):

    grep -P '(?!.*unwanted_word)keyword' file
    

    Demo:

    $ cat file
    foo1
    foo2
    foo3
    foo4
    bar
    baz
    

    Let us now list all foo except foo3

    $ grep -P '(?!.*foo3)foo' file
    foo1
    foo2
    foo4
    $ 
    
    0 讨论(0)
  • 2020-12-12 09:28

    The -v option will show you all the lines that don't match the pattern.

    grep -v ^unwanted_word
    
    0 讨论(0)
  • 2020-12-12 09:29

    The right solution is to use grep -v "word" file, with its awk equivalent:

    awk '!/word/' file
    

    However, if you happen to have a more complex situation in which you want, say, XXX to appear and YYY not to appear, then awk comes handy instead of piping several greps:

    awk '/XXX/ && !/YYY/' file
    #    ^^^^^    ^^^^^^
    # I want it      |
    #            I don't want it
    

    You can even say something more complex. For example: I want those lines containing either XXX or YYY, but not ZZZ:

    awk '(/XXX/ || /YYY/) && !/ZZZ/' file
    

    etc.

    0 讨论(0)
  • 2020-12-12 09:31

    I excluded the root ("/") mount point by using grep -vw "^/".

    # cat /tmp/topfsfind.txt| head -4 |awk '{print $NF}'
    /
    /root/.m2
    /root
    /var
    
    # cat /tmp/topfsfind.txt| head -4 |awk '{print $NF}' | grep -vw "^/"
    /root/.m2
    /root
    /var
    
    0 讨论(0)
提交回复
热议问题