sed パターン間の行数をカウント - 複数のファイル

sed パターン間の行数をカウント - 複数のファイル

1 つのディレクトリに複数のファイルがあります.txt。各ファイルにはセクションがあります。

DONE
item 1
item 2
item 3
DONE

各ファイルの2 つのマーカー間の行数をDONE個別にカウントしたいと思います。

私はこの質問これを作成するには:

sed -n "/DONE/,/DONE/ p" *.txt | wc -l > ~/word_count.txt

しかし、これは各ファイルのカウントを 1 つの数値に結合します。代わりに、次のような出力を希望します。

file1.txt 3
file2.txt 5
file3.txt 6

答え1

より良いawk使い方カウント

awk '
  FNR == 1 {inside = 0}
  $0 == "DONE" {
    if (inside) print FILENAME, n
    n = 0
    inside = ! inside
    next
  }
  inside {n++}' ./*.txt

これにより、各ファイルの各セクションのレコードが印刷されますDONE...DONE。つまり、そのようなセクションがない場合は何も印刷されません。それらを出力するには、 、特殊ステートメントを備えた0の GNU 実装が必要です。awkBEGINFILEENDFILE

awk '
  BEGINFILE {DONE_count = 0}
  $0 == "DONE" {
    if (++DONE_count % 2 == 0) print FILENAME, n
    n = 0
    next
  }
  DONE_count % 2 {n++}
  ENDFILE {if (!DONE_count) print FILENAME, 0}' ./*.txt

または、awkファイルごとに 1 つ実行します。

for file in ./*.txt; do
  awk '
    $0 == "DONE" {
      if (++DONE_count % 2 == 0) print FILENAME, n
      n = 0
      next
    }
    DONE_count % 2 {n++}
    END {if (!DONE_count) print FILENAME, 0}' "$file"
done

答え2

perl -lne '
   eof and !$a && print "$ARGV: ", 0+$a;          # no DONEs => ans=0
   next unless /DONE/ && !$a ... /DONE/;          # skip non-DONE ranges
   /DONE/ and !$a++ && next;                      # begin DONE range
   !/DONE/ and !eof and $a++,next;                # middle of DONE range
   !/DONE/ and eof and $a=2;                      # lone DONE => ans=0
   print "$ARGV: ", ($a-2, $a=0, close ARGV)[0];  # end of DONE range
                                                  # at the end we do 4 things: 1) subtract 2 from sum, 2) print filename+sum, 3) reset sum, and 4) skip the current file and jump to the next file in queue.
' ./*.txt

sedファイルごとにこれを実行できます:

for f in ./*.txt; do
   printf '%s: %d\n' "$f" "$(sed -e '/DONE/,/DONE/!d; //d' "$f" | wc -l)"
done

違いは、完了が完了しないシナリオにあります。

関連情報