awk 出力が検索するファイルの各文字列数を計算します。

awk 出力が検索するファイルの各文字列数を計算します。

できるだけ具体的かつ明確に説明しようとします。

ファイルがあります。log.txt複数の文字列が含まれています。この文字列を検索して印刷して計算します。

一致するファイルの列のみを印刷するコマンドは次のとおりですlog.txt

sed -n '1p' log.txt | awk '{ s = ""; for(i = 25; i <= NF; i++) s = s $i "\n"; print s}'

説明する

sed -n '1p' //prints the first line
awk '{ s = ""; for(i = 25; i <= NF; i++) s = s $i "\n"; print s}' //prints the next columns from the number 25 column

入力する:

Column25 Column26 Column27 ColumnN <--#first filter:I need obtain specific headers.                    ColumnN 
Column25         Column27 ColumnN
        Column26 Column27  <--#Count how many times is repeat every string in whole file

出力:

Column25
Column26
Column27
Column28
Column29
ColumnN

私はこれを試みます:file.log前の出力で同じファイルの同じコマンドですべての偶然の一致を計算したいと思います。

sed -n '1p' log.txt | awk '{ s = ""; for(i = 25; i <= NF; i++) s = s $i "\n"; print s}'

次のように出力に戻します。

希望の出力:

Column25 - n times
Column26 - n times
Column27 - n times
Column28 - n times
Column29 - n times
ColumnN - n times

PS。私は検索を開始するためにforループで同じ変数を使用することを検討しましたが、うまくいきませ"$s"ん。

ベストアンサー1

この問題を解決した方法は次のとおりです。

awk '{n=1;if(NR==1)n=25;for(i=n;i<=NF;i++) a[$i]++} END{for(val in a) print val,a[val]}' input.txt

最初の行でフィールド25以上をキャプチャするには、NR変数を確認し、nループに使用する変数を設定する必要があります。これはa[$i]++、フィールドがキーであり、配列の値が++演算子によって増加される連想配列になります。これはawkの非常に一般的なフィールド計算方法です。

おすすめ記事