首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于第一列的合并文件

基于第一列的合并文件
EN

Stack Overflow用户
提问于 2019-08-24 13:25:30
回答 1查看 143关注 0票数 1

我正在尝试合并两个CSV文件的列。两个CSV文件都具有相同的第1列。我只想通过awk命令来完成

代码语言:javascript
复制
file1.csv

 abc.co.in, AB, ABR,
 def.co.in, DE, DEFF,
 ghi.co.in, AB DEE, GHI,
.....................................

file2.csv

abc.co.in, abc, Linux abc 3.0.101-default 22 16:42:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
def.co.in, def, Linux def 3.0.101-default #1 SMP Mon Aug 13 18:53:23 UTC 2018x86_64 x86_64 x86_64 GNU/Linux
ghi.co.in, ghi1, Linux ghi1 3.0.default #1 SMP Fri Feb 22 16:42:57 UTC 2019x86_64 x86_64 x86_64 GNU/Linux


Expected (final csv file)

abc.co.in, AB, ABR,  abc, Linux abc 3.0.101-default 22 16:42:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
def.co.in, DE, DEFF,  def, Linux def 3.0.101-default #1 SMP Mon Aug 13 18:53:23 UTC 2018x86_64 x86_64 x86_64 GNU/Linux
ghi.co.in, AB DEE, GHI,  ghi1, Linux ghi1 3.0.default #1 SMP Fri Feb 22 16:42:57 UTC 2019x86_64 x86_64 x86_64 GNU/Linux
.....................................

我在下面试过了,但没有完全帮到我

代码语言:javascript
复制
awk 'FNR==NR{a[$1]=$2 FS $3;next}{ print $0, a[$1]}' file2.csv file1.csv
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-24 13:39:00

你能试一下吗。

代码语言:javascript
复制
awk '
BEGIN{
  FS=OFS=","
}
FNR==NR{
  sub(/^ /,"")
  val=$1
  $1=""
  sub(/,/,"")
  sub(/,$/,"")
  a[val]=$0
  next
}
$1 in a{
  $1=$1 OFS a[$1]
  print $0
}'  file1  file2

解释:在这里添加对上述命令的解释。

代码语言:javascript
复制
awk '                      ##Starting awk program here.
BEGIN{                     ##Starting BEGIN section of code here.
  FS=OFS=","               ##Setting FS and OFS as comma for all lines of Input_file here.
}                          ##Closing BEGIN BLOCK of this code here.
FNR==NR{                   ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
  sub(/^ /,"")             ##Substituting initial space of line with NULL for Input_file1.
  val=$1                   ##Creating variable val to $1 of current line.
  $1=""                    ##Nullifying $1 to NULL now.
  sub(/,/,"")              ##Substituting comma very first comma with NULL in current line.
  sub(/,$/,"")             ##Substituting last comma with NULL here.
  a[val]=$0                ##Creating n array with name a whose index is val and value if current line.
  next                     ##next will skip all further statements from here.
}
$1 in a{                   ##Checking condition if $1 of current line is present in array a then do following.
  $1=$1 OFS a[$1]          ##Setting $1 value to $1 OFS a[$1] value here as per OP need.
  print $0                 ##Printing edited current line now.
}'  file1  file2           ##Mentioning Input_file names here.
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57638374

复制
相关文章

相似问题

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