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?

3
  • You say "2nd column" then you say "third column"; which is it?
    – Hello71
    Mar 23, 2011 at 21:41
  • 2nd column. Fixed.
    – roger34
    Mar 23, 2011 at 21:50
  • This question has nothing to do with bash. Jun 16, 2014 at 15:57

4 Answers 4

1

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

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

How about:

awk '$2 != 3' filename
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)

2

You can use:

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

-P is a perl-style regular expression matcher.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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