0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

awk 複数ファイルの取り扱い

Posted at

個人的につまづいたところをピックアップしました。
pythonとか他の言語で書けよって話かもしれませんが、awk好きな人にどうぞ。

#ファイルから1行ずつ読み込む
$0が更新される。

awk 'BEGIN {while ((getline < "file1")>0)
               {
                   action
               }
           }'

ワンライナー
awk 'BEGIN {while((getline<"file1")>0){print $0;}}'

#ファイルから変数xに読み込む。
変数に読み込むことため、$0は更新されない。

awk 'BEGIN {while ((getline x < "file1") >0 ){print x}}'

#ファイルから変数xに読み込み、splitで分割
splitの使い方
split(strings, array, separator)
strings : 分割対象の文字列
array : データの格納先
separator : 区切り文字
array[index]で分割後のデータにアクセス可能

awk 'BEGIN {while ((getline x < "file1") >0 ) {split(x,array);print array[index]}}'

#複数ファイル読み込み(今回は2つのファイル)

awk 'BEGIN {while((getline<"file1")>0)
                {while((getline<"file2")>0)
                    {
                        action
                    }
                }
                close("file2")
            }'
ワンライナー
awk 'BEGIN{while((getline<"file1")>0){while((getline<"file2")>0{print $0}}close("file2")}'

#使用例
while文をネスト

awk 'BEGIN{OFS="\t"; while ((getline<"file1")>0){count=0; while((getline var <"file2")>0){split(var,array); if($2<=array[2] && array[3] <= $3){count++;}}close("file2");print $1, $2,$3,count}}'
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?