Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep pattern to exclude negative numbers from file

I have been struggling trying to come up with an easier answer to this problem. But still using grep.

I want to grep out the positive (and negative numbers) of myfile.dat. Myfile.dat look like this:

-1.4987 4.1354  -8.1235
4.2322  -0.9842 -2.6845
3.6845  1.5132  -2.8452
0.0122  9.3542  -1.2354
-7.2127 -1.1253 -4.3967
0.3535  7.2416  -3.1277

No need to retain column format. So I have used the following grep patterns.

Negative numbers:

grep -E -o [-][0-9]+.[0-9]+ myfile.dat

Positive numbers (here I have to pipe all numbers into another grep):

grep -Eo [-]\?[0-9]+.[0-9]+ myfile.dat | grep -v [-]

Here comes the question! Is there a grep pattern that allows me to extract positive numbers directly, without the use of a second grep command?

This is all about the pattern, not whether I could use another command.

like image 468
user3271410 Avatar asked Feb 04 '14 19:02

user3271410


People also ask

How do I exclude results from grep?

Exclude Words and Patterns To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters).

How do you negate grep?

To use negative matching in grep , you should execute the command with the -v or --invert-match flags. This will print only the lines that don't match the pattern given.

How do I exclude a file type in grep?

To read a list of files to exclude from a file, use --exclude-from FILE .

Which of the grep command option will select non matching lines from given file?

With the -v, --invert-match option (see below), count non-matching lines. (-c is specified by POSIX .)


2 Answers

Using grep -P you can do this to get all positive numbers:

 grep -oP '(?<!-)\b[0-9]+\.[0-9]+\b' file
like image 120
anubhava Avatar answered Sep 23 '22 16:09

anubhava


You could match on beginning-of-line or space before digits:

$ grep -oE '(^| )[0-9]+\.[0-9]+' Myfile.dat | tr -d ' '
4.1354
4.2322
3.6845
1.5132
0.0122
9.3542
0.3535
7.2416

tr -d ' ' just removes any initial spaces from the output, you can skip it if not needed.

like image 24
grebneke Avatar answered Sep 24 '22 16:09

grebneke