Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux grep command

Tags:

linux

grep

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")

like image 201
Hello Avatar asked Apr 01 '26 04:04

Hello


2 Answers

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
like image 51
Haifeng Zhang Avatar answered Apr 02 '26 21:04

Haifeng Zhang


awk fit's pretty good for such cases:

awk '/abc/ && !/xyz$/' input

use awk! :)

like image 40
hek2mgl Avatar answered Apr 02 '26 22:04

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!