首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较两个文件之间的第一列,并将数据从一个文件追加到另一个文件

比较两个文件之间的第一列,并将数据从一个文件追加到另一个文件
EN

Stack Overflow用户
提问于 2020-09-14 12:08:31
回答 1查看 53关注 0票数 2

我有两个文件fileonefile-2如下所示:

代码语言:javascript
复制
fileone:
    a   0   0
    b   4   3
    c   3   2
    f   3   2
filetwo:
    a   3
    b   2
    f   2

如果column1来自fileone,column1来自file-2,那么我需要将column2file-2附加到fileoneE 214,如下所示:

代码语言:javascript
复制
Output:

    a   0   0   3
    b   4   3   2
    c   3   2
    f   3   2   2

我尝试过这样做,但没有获得所需的输出:

代码语言:javascript
复制
#!/bin/bash
echo "These reports are based on this run:" ; pwd
echo " " ;
awk -F, 'FNR==NR {a[$1]; next}; $1 in a' fileone filetwo
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-14 12:14:47

您已经接近了,您传递的Input_file序列应该更改:)以及在尝试中没有字段分隔符作为,

请您试着用所示的样品进行下列、书写和测试。

代码语言:javascript
复制
awk 'FNR==NR{a[$1]=$2;next} {print $0,($1 in a?a[$1]:"")}' Input_file2  Input_file1

解释:添加了上面的详细说明。

代码语言:javascript
复制
awk '                              ##Starting awk program from here.
FNR==NR{                           ##Checking condition which will be TRUE when Input_file2 is being read.
  a[$1]=$2                         ##Creating array a with index of $1 and value of $2 here.
  next                             ##next will skip all further statements from here.
}
{
  print $0,($1 in a?a[$1]:"")      ##Printing current line and checking if 1st field is there in a then print a[$1] or print NULL.
}
' Input_file2  Input_file1         ##Mentioning Input_file names here.

或者,如果您想获得好看的对齐,请尝试column

代码语言:javascript
复制
awk 'FNR==NR{a[$1]=$2;next} {print $0,($1 in a?a[$1]:"")}' file2  file1 | 
column -t
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63884011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档