How can I use the UNIX shell to count the number of times a letter appears in a text file?

后端 未结 10 549
清酒与你
清酒与你 2021-02-03 19:07

I have a few text files and I\'d like to count how many times a letter appears in each?

Specifically, I\'d like to use the UNIX shell to do this, in the form of: cat fil

相关标签:
10条回答
  • 2021-02-03 19:50

    Alternative to grep:

    sed 's/[^x]//g' filename | tr -d '\012' | wc -c
    

    where x is the character you want to count.

    0 讨论(0)
  • Here is another way

    cat  input_file | \
    awk 'BEGIN {FS="x"; var=0 } \
    {if (NF>0){ var=var + (NF-1) } } \
    END{print var}'
    

    where X is the character or string of characters you want to count and infile is the input file

    0 讨论(0)
  • 2021-02-03 19:51
    awk '{ printf "%s\n", gsub( "ur_char", "oth_char", $0 ) }' < your_file_name > output.txt
    

    you can add count of current line number to get the line numbers in awk also.

    0 讨论(0)
  • 2021-02-03 19:53

    There's also awk:

    $ echo -e "hello world\nbye all" | awk -Fl '{c += NF - 1} END {print c}'
    5
    

    Change -Fl to -F<your character>.

    This works by setting the field delimiter to the character specified by -F, then accumulating the number of fields on each line - 1 (because if there's one delimiter, there are two fields - but we should only count 1).

    0 讨论(0)
提交回复
热议问题