
파일의 모든 단어 수를 어떻게 알 수 있나요?
텍스트 파이프나 문서의 각 단어에 대한 히스토그램을 원합니다. 문서에는 새 줄과 빈 줄이 존재합니다. 를 제외한 모든 것을 제거했습니다 [a-zA-Z]
.
> cat doc.txt
word second third
word really
> cat doc.txt | ... # then count occurrences of each word \
# and print in descending order separated by delimiter
word 2
really 1
second 1
third 1
파일이 1GB 텍스트이고 기하급수적인 시간 로드로 작동할 수 없으므로 어느 정도 효율적이어야 합니다.
답변1
이 시도:
grep -o '\w*' doc.txt | sort | uniq -c | sort -nr
-o
일치하는 줄 대신 각 일치 항목을 인쇄합니다.\w*
단어 문자 일치sort
에 파이프하기 전에 일치 항목을 정렬하십시오uniq
.uniq -c
고유한 줄과 발생 횟수를 인쇄합니다.-c
sort -nr
발생 횟수를 기준으로 역 정렬합니다.
산출:
2 word
1 third
1 second
1 really
대안:
awk
정확한 출력을 위해 사용 :
$ grep -o '\w*' doc.txt \
| awk '{seen[$0]++} END{for(s in seen){print s,seen[s]}}' \
| sort -k2r
word 2
really 1
second 1
third 1
답변2
perl -lnE '
$count{$_}++ for /[[:alpha:]]+/g;
END {
say "@$_" for
sort {$b->[1] <=> $a->[1] || $a->[0] cmp $b->[0]}
map {[$_, $count{$_}]}
keys %count
}
' doc.txt
이는 pLumo의 초기 솔루션보다 훨씬 더 많은 메모리를 소비합니다.