使用AWK处理来自多个文件输入 [英] Using AWK to Process Input from Multiple Files

查看:102
本文介绍了使用AWK处理来自多个文件输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多人都非常有帮助张贴在一次AWK'ing多个输入文件以下解决方案:

  $ AWK'FNR == {NR一个[$ 1] = $ 16 $ FS 3;接下来} {$打印0时,[$ 1]}'文件2文件1

这工作得很好,但我想知道我是否有人可以给我解释一下为什么?我觉得AWK语法有点很难找到窍门,并希望有人不介意突破code片段下来我。感谢您的时间和帮助!


解决方案

 的awk'FNR == {NR一个[$ 1] = $ 16 $ FS 3;接下来}

在这里,我们处理的第一个输入(文件2)。比方说,FS的空间,我们建立一个数组( A )后,指数COLUMN1,值列2栏3 FNR == NR和明年手段,$这部分C $ CS只为file2的工作。你可以GAWK男人检查什么是NR和FNR

  {$打印0时,[$ 1]}'文件2文件1

NR!= FNR 它的时间来处理输入第二,文件1。在这里我们打印文件1线,并采取COLUMN1为指标,找出阵列(一)打印的值。在另一个词,文件1和文件2被COLUMN1在两个文件中加入。

有关NR和FNR,不久,

  1输入有5条线路
第二个输入有10条线,NR是1,2,3 ... 15
FNR是1 ... 5然后1 ... 10

您看到 FNR的把戏== NR 支票。

Many people have been very helpful by posting the following solution for AWK'ing multiple input files at once:

    $ awk 'FNR==NR{a[$1]=$2 FS $3;next}{ print $0, a[$1]}' file2 file1

This works well, but I was wondering if I someone could explain to me why? I find the AWK syntax a little bit tough to get the hang of and was hoping someone wouldn't mind breaking the code snippet down for me. Thank you for your time and help!

解决方案

awk 'FNR==NR{a[$1]=$2 FS $3;next}

here we handle the 1st input (file2). say, FS is space, we build an array(a) up, index is column1, value is column2 " " column3 the FNR==NR and next means, this part of codes work only for file2. you could man gawk check what are NR and FNR

{ print $0, a[$1]}' file2 file1

When NR != FNR it's time to process 2nd input, file1. here we print the line of file1, and take column1 as index, find out the value in array(a) print. in another word, file1 and file2 are joined by column1 in both files.

for NR and FNR, shortly,

1st input has 5 lines
2nd input has 10 lines,

NR would be 1,2,3...15
FNR would be 1...5 then 1...10

you see the trick of FNR==NR check.

这篇关于使用AWK处理来自多个文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆