
많은 숫자가 포함된 파일이 있습니다(숫자만 있고 각 숫자는 한 줄에 있음). 숫자가 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보다 클 때마다 변수는
c
1씩 증가합니다.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