テキストファイルの2番目の列の各行に対してゼロ以外の数値を計算します。

テキストファイルの2番目の列の各行に対してゼロ以外の数値を計算します。

次のように、各行の単語がコンマで区切られたテキストファイルがあります。

7022122465,0,\N,,0,2015-09-29 10:48:33
7022597642,0,\N,,0,2015-09-29 10:48:33
7022848906,0,\N,,0,2015-09-29 10:48:33
7022848906,5,\N,,0,2015-09-29 10:48:33
7022848906,55,\N,,0,2015-09-29 10:48:33
.....................................etc

Linux / UNIXでは、orコマンドのみを使用してsed2番目の列のゼロ以外の数値を計算したいと思います。grep

ノート

他のコマンドは使用されません。

cut -d',' -f2 < KAR_UBONA_UBONACT15_20150929_20150930_FEEDBACK.txt | grep -vcw 0

しかし、私はそれを望むのではなく、cutそれを使うべきですgrep

ベストアンサー1

grepオプションを使用できます-c。以下を使用して、最初のカンマの前のすべての文字と2番目のコンマの後のすべての文字を削除できますsed

sed 's/^[^,]*,//;s/,.*//' < the_file | grep -c -E '[^0]'

編集:このsedコマンドはあなたのコマンドと同じことを行いますので、元のコマンドもcut使用できます。grep

EDIT2:1つのコマンドのみを使用したい場合は、@cuonglm grp回答を使用できます。ただ使いたいなら電話1本最終行数を要約するには、sedラベルに多くの作業を行う必要があります。

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_file

これで、パイプで接続したり、コマンドを複雑な魔法に置き換えることで数字を集計できるbcと聞いたので、可能になります。psedsedsed

ただ使いたいならプログラム( sed) でも何度も呼び出しても大丈夫です。はるかに簡単です。

sed '/^[^,]*,0,.*/d' < the_file | sed -n '$='

おすすめ記事