#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?

link|improve this question
feedback

4 Answers

up vote 1 down vote accepted

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
link|improve this answer
Thank you, -P is what I need! :) – Putnik Jan 19 at 18:51
feedback

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.

link|improve this answer
1  
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 at 16:56
It works too, thank you. Unfortunatelly I can't mark more than 1 answer as accepted. – Putnik Jan 19 at 18:53
feedback

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
link|improve this answer
feedback

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}'
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.