2
#cat sample
1   -1  2
2   2   2
2   1-1 3

I need to get all the lines that contains negative value, that is 1st line only. Values are tab-separated. First I tried

# grep "\-1" sample
1   -1  2
2   1-1 3

But if I try

 grep "\t\-1" sample

I get nothing (no match). What am I doing wrong?

HopelessN00b
  • 53,795
  • 33
  • 135
  • 209
Putnik
  • 2,217
  • 4
  • 27
  • 43

4 Answers4

3

In Bash, you can do this:

grep $'\t-1' sample

The $'' causes escapes to be interpreted.

It's not necessary to escape the minus sign.

Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151
  • 2
    This reminds me: everyone should go and (re)read bash documentation every once in a while. You sort of discover something that you didn't know before every time. – cjc Jan 19 '12 at 16:56
  • It works too, thank you. Unfortunatelly I can't mark more than 1 answer as accepted. – Putnik Jan 19 '12 at 18:53
1

Try something like:

grep -P '\t-1' sample

By the way, the sample you've provided is tab-indented. You may try the following for generic whitespace matching:

grep -P '\s-1' sample
Georgi Hristozov
  • 712
  • 1
  • 4
  • 13
1

There is no facility for \t being tab in basic regular expressions (those described by man 7 regex). As Georgi Hristozov pointed out, you can use Perl Compatible Regular Expressions to get this ability. Some implementations of grep won't support -P, but other basic tools will have more rich regular expression languages, here are some examples which should work:

sed -n '/\t-/p' sample
awk '/\t-/' sample
perl -ne '/\t-/ && print' sample

In order to get it working with regular grep (without using pcre) you are going to have to put a literal tab expression in your regex. In many shells where the tab key does something like completion, you can get a literal tab character with Ctrl-v<tab>. so you'd type:

grep 'Ctrl-v<tab>-' sample
stew
  • 9,388
  • 1
  • 30
  • 43
1

Check man 7 regex for the POSIX regular expressions you can use, while -P for PCRE is supported in lots of places its not available everywhere (and the manualpage says its buggy so I don't always trust it myself) the POSIX ones should work in more places.

You can try something like this:

grep "^[[:digit:]]\+[[:space:]]\+-"

^ matches the beginning of the line.
[[:digit:]]\+ matches one or more digits.
[[:space:]]\+ matches one or more whitespace characters.
- finally matches the negative value you were looking for.

Manual page for regex(7): http://linux.die.net/man/7/regex

Optional solution:

You can use awk to do this too (and certainly other tools). This is an awk example that prints lines where the second column is less than 0 (negative):

awk '{if ($2 < 0) print}'
Mattias Ahnberg
  • 4,139
  • 19
  • 19