#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?
In Bash, you can do this:
The
$''
causes escapes to be interpreted.It's not necessary to escape the minus sign.
Try something like:
By the way, the sample you've provided is tab-indented. You may try the following for generic whitespace matching:
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: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: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:
^
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):