4

Is there an inbuilt command to do this or has anyone had any luck with a script that does it?

I am looking to count the number of times a certain string (not word) appears in a file. This can include multiple occurrences per line so the count should count every occurrence not just count 1 for lines that have the string 2 or more times.

For example, with this sample file:

blah(*)wasp( *)jkdjs(*)kdfks(l*)ffks(dl
flksj(*)gjkd(*
)jfhk(*)fj (*) ks)(*gfjk(*)

If I am looking to count the occurrences of the string (*) I would expect the count to be 6, i.e. 2 from the first line, 1 from the second line and 3 from the third line. Note how the one across lines 2-3 does not count because there is a LF character separating them.

Update: great responses so far! Can I ask that the script handle the conversion of (*) to \(*\), etc? That way I could just pass any desired string as an input parameter without worrying about what conversion needs to be done to it so it appears in the correct format.

4

6 に答える 6

22

grepやなどの基本的なツールを使用できますwc

grep -o '(\*)' input.txt | wc -l
于 2012-04-12T08:08:37.940 に答える
6

perl の「Eskimo kiss」演算子を-nスイッチで使用して、最後に合計を出力します。\Q...\Eメタ文字を無視するために使用します。

perl -lnwe '$a+=()=/\Q(*)/g; }{ print $a;' file.txt

脚本:

use strict;
use warnings;

my $count;
my $text = shift;

while (<>) {
    $count += () = /\Q$text/g;
}

print "$count\n";

使用法:

perl script.pl "(*)" file.txt 
于 2012-04-12T09:40:31.980 に答える
2

これはファイルの行をループし、各行で文字列 "(*)"のすべての出現箇所を検索します。その文字列が見つかるたびに、$cがインクリメントされます。ループする行がなくなると、$cの値が出力されます。

perl -ne'$c++ while /\(\*\)/g;END{print"$c\n"}' filename.txt

更新:これを引数として正規表現を受け入れるソリューションに変換するように求めるコメントに関しては、次のようにすることができます。

perl -ne'BEGIN{$re=shift;}$c++ while /\Q$re/g;END{print"$c\n"}' 'regex' filename.txt

それでうまくいくはずです。perlrunをもう一度読み飛ばしたいと思った場合は、よりエレガントな解決策が見つかるかもしれませんが、これでうまくいくはずです。

正規表現にリストコンテキストを提供することで、明示的な内部whileループを削除して、暗黙的なループを優先することもできます。

perl -ne'BEGIN{$re=shift}$c+=()=/\Q$re/g;END{print"$c\n"}' 'regex' filename.txt

于 2012-04-12T08:05:49.560 に答える
1

基本的なgrepコマンドを使用できます。

:ファイル中の「hello」単語の出現回数を知りたい場合

grep -c "hello" filename

パターンの出現回数を知りたい場合は、

grep -c -P "Your Pattern"

パターン例 : hell.w、\d+ など

于 2016-06-02T15:18:43.573 に答える
0

以下のコマンドを使用して、ファイル内の特定の文字列数を見つけました

grep search_String ファイル名|wc -l

于 2017-01-12T07:02:50.840 に答える
-1
text="(\*)"
grep -o $text file | wc -l

次のような引数を受け入れるスクリプトにすることができます。

スクリプト:

#!/bin/bash
text="$1"
file="$2"
grep -o "$text" "$file" | wc -l

使用法:

./count "(\*)" file_path
于 2015-04-27T11:25:31.520 に答える