How to grep for a line that has the same number you both need and don't need

2

This isn't at all easy to explain but easy to just show.

I have lines in a file such as:

100Dollars              3              IP  
200Dollars              3              IP
300Dollars              4              IP

I need to grep for lines that have no '3' in the second column. I tried the following:

egrep -v '3' filename

However this does not return the third line due to having a 3 in the first part of it. There's my basic question, if that makes sense.

How do I exclude what is in the first column and only grep for whatever is in the second column?

roger34

Posted 2011-03-23T21:32:42.013

Reputation: 55

You say "2nd column" then you say "third column"; which is it? – Hello71 – 2011-03-23T21:41:52.820

2nd column. Fixed. – roger34 – 2011-03-23T21:50:37.590

This question has nothing to do with bash. – Scott – 2014-06-16T15:57:29.660

Answers

1

Can't you just do grep -v " 3 ", assuming the columns are delimited by spaces?

Hello71

Posted 2011-03-23T21:32:42.013

Reputation: 7 636

Gave this a shot, does not work. Opened the file in vim and it looks like it is separated by tabs in the columns, not spaces. – roger34 – 2011-03-23T21:47:40.320

@roger34: Then use tabs... duh. – Hello71 – 2011-03-23T21:49:12.187

Did, it didn't work. – roger34 – 2011-03-23T21:53:17.323

1Try grep -v '[[:space:]]3[[:space:]]' or grep -v '\<3\>'. – Mikel – 2011-03-23T22:08:12.840

Mikel the second regex worked. Thanks. Now I have to investigate why it works and learn from it. – roger34 – 2011-03-23T22:12:29.093

@roger34 the metacharacters < and > match 'beginning of word' and 'end of word'. So it can match a bare 3, but not with 300, since the 3 in 300 is not end of anything. – Rich Homolka – 2011-03-23T22:18:09.887

5

How about:

awk '$2 != 3' filename

Hai Vu

Posted 2011-03-23T21:32:42.013

Reputation: 4 824

2

I think you want to step up to awk or grep, which can do columns (among many other things)

gawk '$1 ~ /3/ && $2 !~ /3/{print $0}' < filename

Should do it.

This looks for a 3 in the first column (Columns are numbered starting by 1 in awk, $0 is the whole line) and not a 3 in the second column, and if so print the whole line ($0)

Rich Homolka

Posted 2011-03-23T21:32:42.013

Reputation: 27 121

2

You can use:

grep -v -P '\t3\t' filename

-P is a perl-style regular expression matcher.

Resorath

Posted 2011-03-23T21:32:42.013

Reputation: 1 027