根据第一个字段匹配行并合并第二个字段 [英] Match rows based on first field and combine second field
问题描述
我想使用awk,sed或类似方法合并两个文件中第二个字段的条目.
I would like to combine entries from the second field from two files using awk, sed or similar.
文件0:
string:data:moredata
文件1:
string:random:moredata
如果第一个字段 file0 中的 string 在 file1 中具有匹配的条目,则打印
If the first field, string in file0 has a matching entry in file1 then print
$random:$data
选择字段似乎很简单:
$ awk -F':' '{print $2}' filename
需要匹配行并打印匹配列$ 2
Need to match rows and print matching column $2
推荐答案
如何解决这个问题-
awk -F":" 'NR==FNR {x[$1] = $0; y[$1] = $2; next} ($1 in x) {print $2":"y[$1]}' file1 file2
执行:
[jaypal~/Temp]$ cat file1
string:data:moredata
[jaypal~/Temp]$ cat file2
string:random:moredata
[jaypal~/Temp]$ awk -F":" 'NR==FNR {x[$1] = $0; y[$1] = $2; next} ($1 in x) {print $2":"y[$1]}' file1 file2
random:data
在此解决方案中,我们将整个file1记录加载到索引为第1列的数组中.我们快速检查下一个文件,以查看第1列是否存在.如果是,则执行print语句.
In this solution, we are loading the whole record of file1 in to the array indexed at column 1. We do a quick check in the next file to see if the column 1 is present. If it is then print statement is executed.
否定测试:
[jaypal~/Temp]$ cat file1
string:data:moredata
man:woman:child
[jaypal~/Temp]$ cat file2
man:random:moredata
string:woman:child
[jaypal~/Temp]$ awk -F":" 'NR==FNR {x[$1] = $0; y[$1] = $2; next} ($1 in x) {print $2":"y[$1]}' file1 file2
random:woman
woman:data
只需在解释中添加一下,NR和FNR是awk的内置变量.NR给出行号,并且在两个文件之间循环时不会重置为0.相反,FNR也是一个行号,当第二个文件开始时,该行号将重置为0.因此,这允许我们将文件1存储到数组中,因为仅当NR == FNR时才执行该操作.这种情况一旦变为假,就意味着第二个文件已经启动,并且下一个模式动作语句开始执行.
这篇关于根据第一个字段匹配行并合并第二个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!