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 file | .... do stuff...
Is there a way I can get the wc command to do this?
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 file | .... do stuff...
Is there a way I can get the wc command to do this?
grep char -o filename | wc -l
grep <string> -o <file> | wc -l
is the generic version. Eg: grep , -o myfile.txt | wc -l
counts the number of commas in myfile.txt and grep abcd -o myfile.txt | wc -l
counts the number of abcd
s in myfile.txt
grep -c
doesn't count multiple occurrences on the same line, unfortunately
Apr 7, 2016 at 11:59
Another alternative:
tr -d -C X <infile | wc -c
where X is the character or string of characters you want to count and infile is the input file.
grep -o
is newline-separated). This also works with ANY character (including \n
)
Apr 7, 2016 at 12:05
-d
) everything except for characters of type X (-C
), then count the number of remaining characters (wc -c
)."
Alternative to grep:
sed 's/[^x]//g' filename | tr -d '\012' | wc -c
where x
is the character you want to count.
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).
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.
echo "a/b/c/d/e/f/g" | awk -F"/" '{print NF}'
this will give the number of occurrence of character "/"
In this case, i'am counting the character "|":
expr `wc -c < filename` \- `tr -d \| < filename | wc -c`
You can try easily:
grep -c 'YOUR LETTER' YOUR FILE
try it with
grep [PATTERN] -o [FILE] | wc -l
and please do not use cat if not needed.
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