2 つのファイルを扱う方法
前日の2 つのファイルの比較 - 日本 GNU AWK ユーザー会 0.2からの続きです。
$ cat input1.txt data=23 data=33 data=4
と
$ cat input2.txt data=23 data=32 data=3
という 2 つのファイルがあった際に、値を比較するというものですが、Janis Papanagnou が答えてくれているので全てです。
# condition where you are in the first file; NR==FNR NR==FNR { mem[NR] = $0; next } # because of the 'next' you are now in the second file; NR!=FNR mem[FNR] != $0 { print "Some message for line " FNR }
良く awk 本にも出てくるようなものですが、とっさに思いつかない部分ですが、コメント付きで書かれています。
この場合であれば、diff でも問題ないという意見も出ています。
また、長いものでは以下のようなものもあります。
function printmsg(n1, n2, nth) { if (n1 == n2) printf "line %d missing in the %s file\n", n1, nth else printf "lines %d - %d missing in the %s file\n", n1, n2, nth } ARGIND == 1 { a[NR] = $0 next } FNR in a && a[FNR] != $0 { printf "difference in line %d\n", FNR } END { n = NR - FNR if (n < FNR) printmsg(n + 1, FNR, "first") else if (FNR < n) printmsg(FNR + 1, n, "second") }
BEGIN { file2 = ARGV[ ARGC - 1 ] ARGC-- } { getline line <file2 if ( $0 != line ) print "-->", line }
後者のものはまさにgetline 中の getline - 日本 GNU AWK ユーザー会 0.2でコメントをいただいたファイルのオープン中に getline を使う方法ですね。