Search code examples
linuxgrep

Linux grep command


Can I use grep command to look for all the lines in a file that have"abc" in them, but exclude the lines that end in say "xyz"?

Eg grep 'abc' fileName (some way to exclude all lines ending in "xyz")


Solution

  • Try this:

    hzhang@dell-work ~ $ cat sample.csv 
    abc, xyz
    abc,1
    abc,2
    abc,3,xyz
    hzhang@dell-work ~ $ grep abc sample.csv |grep -v "xyz$"
    abc,1
    abc,2
    

    The explanation of -v:

    -v, --invert-match
                  Invert the sense of matching, to select non-matching lines.  (-v is specified by POSIX.)
    

    If you can use awk, just check the patterns:

    hzhang@dell-work ~ $ awk '/abc/ && !/xyz$/' sample.csv 
    abc,1
    abc,2