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?

link|improve this question
You say "2nd column" then you say "third column"; which is it? – Hello71 Mar 23 '11 at 21:41
2nd column. Fixed. – roger34 Mar 23 '11 at 21:50
feedback

4 Answers

up vote 1 down vote accepted

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

link|improve this answer
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 Mar 23 '11 at 21:47
@roger34: Then use tabs... duh. – Hello71 Mar 23 '11 at 21:49
Did, it didn't work. – roger34 Mar 23 '11 at 21:53
1  
Try grep -v '[[:space:]]3[[:space:]]' or grep -v '\<3\>'. – Mikel Mar 23 '11 at 22:08
Mikel the second regex worked. Thanks. Now I have to investigate why it works and learn from it. – roger34 Mar 23 '11 at 22:12
show 2 more comments
feedback

How about:

awk '$2 != 3' filename
link|improve this answer
feedback

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)

link|improve this answer
feedback

You can use:

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

-P is a perl-style regular expression matcher.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.