Grep remove line with 0 but not 0.2?

grep -vx 0

From man grep:

-x, --line-regexp
       Select only those matches that exactly match the whole line.
       For a regular expression pattern, this is like parenthesizing
       the pattern and then surrounding it with ^ and $.

-w fails because the first 0 in 0.02 is considered a "word", and hence this line is matched. This is because it is followed by a "non-word" character. You can see this if you run the original command without -v, i.e. grep -w "0".


With grep:

grep -v "^0$" file

^ means beginning of the line, $ means end of the line.


While grep can be used for this (as other answers clearly show), let’s take a step back and think about what you actually want:

  • You have a file containing numbers
  • You want to perform filtering based on the numeric value.

Regex interpret character sequence data. They don’t know about numbers, only about individual digits (and regular combinations thereof). Although in your particular case there’s a simple hack around this limitation, it’s ultimately a requirement mismatch.

Unless there’s a very good reason to use grep here (e.g. because you’ve measured it, and it’s vastly more efficient, and efficiency is crucial in your case), I recommend using a different tool.

awk, for instance, can filter based on numeric comparisions, e.g.:

awk '$1 == 0' your_file

But also, to get all lines containing numbers greater than zero:

awk '$1 > 0' your_file

I love regex, it’s a great tool. But it’s not the only tool. As the saying goes, if all you have is grep, everything looks like a regular language.

Tags:

Grep