1

Could I get some help please with my problem? I have a file that looks like this (comma separated):

A,250,13,820,0,80,201  
B,0,0,0,0,3,0  
C,0,2,1,0,0,0  
D,0,1,105,0,0,10  

I would like to remove a line if it has 5 true zero values, in this case line B. The end file should look like:

A,250,13,820,0,80,201  
C,0,2,1,0,0,0  
D,0,1,105,0,0,10

I have difficulties writing the code because awk always accounts for all zeros (every line has five zero values, but only line B has five true zeros). Would it be easier with a perl script?

  • 1
    WOOOO, You guys are rockstars. Nailed it. I actually used awk from Glenn, because I am more familiar with it. Totally works. I am sure that the perl solution is as good as the awk ;). Thanks a lot. That was soo fast! – P. HamB Mar 16 '16 at 22:42
1

with awk

awk -F, '{z=0; for (i=2; i<=NF; i++) if ($i == 0) z++} z != 5' file > newfile
3

Perl to the rescue!

perl -aF, -ne 'print unless 5 == grep /^0$/, @F;' < input > output
  • -n reads the input line by line
  • -a splits each line into the @F array
  • -F specifies how to split (on a comma in this case)
  • grep used in scalar context returns the number of hits.
1

Provided that no other number than 0 starts with 0 in your file and that the first field is not a number like in your sample, you could do:

sed -ne 's/,0//5;t' -e p < input > output

Note that it deletes those lines that have at least 5 zeros.

With your sample again, a:

grep ',.*[1-9].*,.*[1-9]'

would also do it (searches for two non-zero fields after the first one).

  • That grep command is genius. Great example of simplifying a problem by inverting the requirements. – glenn jackman Mar 16 '16 at 21:25
0
awk 'gsub(/,0/, ",0", $0) != 5' data.input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.