awk:コマンドで定義された変数から名前が由来するファイルとして印刷

awk:コマンドで定義された変数から名前が由来するファイルとして印刷

私は学んでいますawk。私の問題の解決策を見つけようとして、私は次のコードを見つけましたが、最後に停止しました1.説明:

内容file:

H|20200425|abcd|    # header
R|abc|2019-03-06|100.00
R|abc|2019-03-06|15.00
R|abc|2019-03-06|10.00
  • 最後に追加

    T|20200425|-count of records-|-sum of 4th column-
    
  • 20190306.txt出力をYYYYMMDD形式の3列目の日付であるファイルに送信します。

私の試み:

awk -F'|' '
  # get the date formatted
  NR == 2 { 
    d = $3; gsub(/-/,"",d) 
  } 
  # get the 2nd field of the header
  NR == 1 { 
    a = $2 
  } 
  # if the line starts with 'R', sum the column and get the count of them
  $1 == "R" { 
    sum += $4
    ++c 
  } 
  # print the final line with variables acquired
  END { 
    OFS = "|"; print "T",a,c,sum".00" 
  }1
' file

このコマンドは「予想」結果を提供します。

H|20200425|abcd|    
R|abc|2019-03-06|100.00
R|abc|2019-03-06|15.00
R|abc|2019-03-06|10.00
T|20200425|3|125.00

変数dはです20190306

しかし、私が尋ねている質問は、この出力をファイルにリダイレクトする方法です20190306.txt


「もちろん、これは誤ったコーディングです。ため息をつく、Brainache)、しかし私の目標は可能な限り問題に集中することであり、すべてのバグを指摘するように要求するわけではありません。

ベストアンサー1

暗黙的な印刷ジョブ(modeによってトリガーされる)を明示的な印刷ジョブに置き換えることで、d名前がawk変数に格納されているファイルにレコードを印刷できます。1{print > d}

d難しいのは、2番目のレコードが処理されるまで値がわからないため、それまでヘッダーレコードを保存する必要があることです。

たとえば、

$ awk -F'|' '
  # get the 2nd field of the header
  NR == 1 { 
    a = $2 
    h = $0
    next
  } 
  # get the date formatted
  NR == 2 { 
    d = $3; gsub(/-/,"",d) 
    print h > d
  } 
  # if the line starts with 'R', sum the column and get the count of them
  $1 == "R" { 
    sum += $4
    ++c 
  } 
  {
    print > d
  }
  # print the final line with variables acquired
  END { 
    OFS = "|"; print "T",a,c,sum".00" > d
  }
' file

おすすめ記事