100보다 큰 숫자가 포함된 행 수 계산

100보다 큰 숫자가 포함된 행 수 계산

많은 숫자(숫자만 있고 각 숫자가 한 줄에 있음)가 포함된 파일이 있습니다. 숫자가 100(또는 실제로는 다른 값)보다 큰 행 수를 찾고 싶습니다. 어떻게 해야 하나요?

답변1

이 테스트 파일을 고려해 보겠습니다.

$ cat myfile
98
99
100
101
102
103
104
105

이제 100보다 큰 숫자가 포함된 행 수를 계산해 보겠습니다.

$ awk '$1>100{c++} END{print c+0}' myfile
5

어떻게 작동하나요?

  • $1>100{c++}

    줄의 숫자가 100보다 클 때마다 변수는 c1씩 증가합니다.

  • END{print c+0}

    파일 읽기가 끝나면 변수가 c인쇄됩니다.

    0에 추가하면 awk가 이를 숫자로 처리 c하도록 강제합니다 . c숫자가 있는 행이 있으면 이미 숫자 >100입니다 c. 그렇지 않은 경우 c비어 있는 것입니다(팁:이루발). 여기에 0을 추가하면 빈 문자열을 a 로 변경하여 0더 정확한 출력을 제공합니다.

답변2

유사한 솔루션perl

$ seq 98 105 | perl -ne '$c++ if $_ > 100; END{print $c+0 ."\n"}'
5


속도 비교:3회 연속 실행에 대해 보고된 숫자

임의의 문서:

$ perl -le 'print int(rand(200)) foreach (0..10000000)' > rand_numbers.txt
$ perl -le 'print int(rand(100200)) foreach (0..10000000)' >> rand_numbers.txt

$ shuf rand_numbers.txt -o rand_numbers.txt 
$ tail -5 rand_numbers.txt 
114
100
66125
84281
144
$ wc rand_numbers.txt 
20000002 20000002 93413515 rand_numbers.txt
$ du -h rand_numbers.txt 
90M rand_numbers.txt

그리고awk

$ time awk '$1>100{c++} END{print c+0}' rand_numbers.txt 
14940305

real    0m7.754s
real    0m8.150s
real    0m7.439s

그리고perl

$ time perl -ne '$c++ if $_ > 100; END{print $c+0 ."\n"}' rand_numbers.txt 
14940305

real    0m4.145s
real    0m4.146s
real    0m4.196s

재미로 grep(고쳐 쓰다: LC_ALL=C인 경우 Perl보다 훨씬 빠릅니다.

$ time grep -xcE '10[1-9]|1[1-9][0-9]|[2-9][0-9]{2,}|1[0-9]{3,}' rand_numbers.txt 
14940305

real    0m10.622s

$ time LC_ALL=C grep -xcE '10[1-9]|1[1-9][0-9]|[2-9][0-9]{2,}|1[0-9]{3,}' rand_numbers.txt
14940305

real    0m0.886s
real    0m0.889s
real    0m0.892s

sed전혀 재미가 없습니다:

$ time sed -nE '/^10[1-9]|1[1-9][0-9]|[2-9][0-9]{2,}|1[0-9]{3,}$/p' rand_numbers.txt | wc -l
14940305

real    0m11.929s

$ time LC_ALL=C sed -nE '/^10[1-9]|1[1-9][0-9]|[2-9][0-9]{2,}|1[0-9]{3,}$/p' rand_numbers.txt | wc -l
14940305

real    0m6.238s

관련 정보