I have a text file in that each line words are separated by commas, like this:7022122465,0,\N,,0,2015-09-29 10:48:337022597642,0,\N,,0,2015-09-29 10:48:337022848906,0,\N,,0,2015-09-29 10:48:337022848906,5,\N,,0,2015-09-29 10:48:337022848906,55,\N,,0,2015-09-29 10:48:33.....................................etcI want to count non-zero numbers of second column using only sed or grep command in Linux/UNIX.NoteWithout using other commands:cut -d',' -f2 < KAR_UBONA_UBONACT15_20150929_20150930_FEEDBACK.txt | grep -vcw 0But I don't want cut only, I need to use grep.
Count non-zero numbers for each row of a second column in a text file
text processing;sed;grep
You can use the -c option of grep. And you can remove all chars up to the first comma and everything from the second comma on with sed:sed 's/^[^,]*,//;s/,.*//' < the_file | grep -c -E '[^0]'EDIT: This sed command does the same as your cut command so you should also be able to use your original grep command.EDIT2: If you want to use only one command you can use @cuonglm grp answer. If you want to use only one invocation of sed it will be a lot of work with labels in order to sum up the line count at the end. sed -E -n '    s/^[^,]*,[^0,]+,.*/+1/   # replace the lines we are interested in with +1    T delete_line            # if we did not do a substitution right now we jump to delete_line    H                        # we did not jump (so we did the substitution and append the +1 to the hold space    : delete_line            # the label, here we do nothing (silently drop the current line)    $ {                      # on the last line we ...        s/.*/0/              # replace the whole line with 0        G                    # append the hold space (all the +1 from before)        s/\n//g              # remove all newlines        p                    # print the line    }' < the_fileThis can now be piped to bc or you can replace the p command with some complicated sed magic to sum up these numbers in sed. I believe I have heard that sed is turing complete so it should be possible.If you only want to use one program (sed) but do not care to invoke it several times its much easier:sed '/^[^,]*,0,.*/d' < the_file | sed -n '$='