I was wondering how to count the number of a specific character in each line by some text processing utilities?
For example, to count "
in each line of the following text
"hello!"
Thank you!
The first line has two, and the second line has 0.
Another example is to count (
in each line.
You can do it with sed
and awk
:
$ sed 's/[^"]//g' dat | awk '{ print length }'
2
0
Where dat
is your example text, sed deletes (for each line) all non-"
characters and awk
prints for each line its size (i.e. length
is equivalent to length($0)
, where $0
denotes the current line).
For another character you just have to change the sed expression. For example for (
to:
's/[^(]//g'
Update: sed
is kind of overkill for the task - tr
is sufficient. An equivalent solution with tr
is:
$ tr -d -c '"\n' < dat | awk '{ print length; }'
Meaning that tr
deletes all characters which are not (-c
means complement) in the character set "\n
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다