Nadav
Nadav

Reputation: 2717

bash problem with grep

Whenever i write grep -v "0" in order to ignore the 0 number somehow the number 10 is getting ignored as well.

Please help me use the grep -v "0" with ignoring 0 in the process and not ignoring 10

Upvotes: 0

Views: 382

Answers (4)

Shawn D.
Shawn D.

Reputation: 8125

So, grep works on a line-by-line basis. If something in the line matches, it matches the line. Since you've said to invert the set of matches (-v), it doesn't show anything containing a 0 in the line, which 10 contains.

If you just have line-by-line output like

0
1
2
3
4
<whatever>
10
11

and you just want to ignore anything that is solely '0',

you can do something like

grep -v "^0$"

I created a file containing some numbers

cat numbers.txt 
0
1
5
10
11
12

then ran the grep.

grep -v "^0$" numbers.txt 
1
5
10
11
12

Is that what you want?

Upvotes: 2

thinice
thinice

Reputation: 710

Assuming it's in a line similar to this:

12 0 5 10

You can simply pad the 0 in with the grep: grep -v " 0 "

Upvotes: 0

Eric Darchis
Eric Darchis

Reputation: 26657

You could use the whole-word:

grep -vw 0

This would allow 10 but not 0.1

Upvotes: 3

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94103

grep "0" will match any line that has a 0 in it, so the negation of that will not match any line that has a 0 in it. Since 10 has a zero in it, it will be "ignored".

You need to surround your 0 with word boundaries (\b) which tells the regex engine that there can't be a word character ([a-z0-9]) before or after your zero: grep "\b0\b"

Note that grep works by line so if a line contains 10 and 0, it will not be matched.

Upvotes: 3

Related Questions