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.
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).
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.
To read a list of files to exclude from a file, use --exclude-from FILE .
With the -v, --invert-match option (see below), count non-matching lines. (-c is specified by POSIX .)
Using grep -P
you can do this to get all positive numbers:
grep -oP '(?<!-)\b[0-9]+\.[0-9]+\b' file
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With