views:

253

answers:

3

I get results like below from a pipeline in linux:

1 test1
1 test2
2 test3
1 test4
3 test5
1 test6
1 test7

How can I use grep to retrieve only the lines where the first column is > 1?

+1  A: 

use the "^" char, it marks the beginning of a line

-v will not include lines starting with 1

include the extra space, so it will exclude lines like "1 asd" but not "12 asd"

grep -v "^1 "
Am
ok, but how I can add the > 1 condition to that?
goe
grep "^[23456789] "
Am
strike that, bad example
Am
What's 23456789 in this example?
goe
it means any of this characters, so any digit char is valid
Am
ok, but then this doesn't really support the column > 1 requirement
goe
ur right, i updated the answer
Am
Actually grep -v "1 " worked for me fine! THANKS
goe
+6  A: 

Don't use grep for this. Try awk instead:

 <pipeline> | awk '$1>1 {print $0}'
dmckee
I can't use awk, it has to be one of the standard tools
goe
awk is standard. it's available on every *nix
elcuco
awk is a 'standard tool', in that it's part of the POSIX standard and should be present on any UNIX-like system which you'd expect to find grep. grep only deals with strings characters, not numbers, and so doesn't have a concept of 'greater than'.
Stephen Veiss
I get that, but for this task I was asked not to use it.
goe
@dmckee: beautiful solution. You can shorten the awk script to '$1>1' -- the default is to print out the line.
Hai Vu
You know, I kind of picked up awk as I went along, and never knew ther *was* a default action. You learn something every day.
dmckee
sounds like this is homework to teach you about regexes
IanNorton
+3  A: 
grep -v "^1"
  • -v selects non-matching lines
  • ^ is the start of a line

EDIT: As pointed out in the comments, this solution does not filter out lines starting with multi-digit numbers. Adding a space after the 1 solves the problem:

grep -v "^1 "
Dawie Strauss
It doesn't seem to be working as column > 1 condition
goe
Actually grep -v "1 " worked for me fine! THANKS
goe
This solution does not work for numbers that starts with '1': 10, 11, 100, ...
Hai Vu
@goe, @Hai Vu: Thanks for pointing out the problem with multi-digit numbers. I edited the answer to account for it.
Dawie Strauss