首页 > 解决方案 > awk 在第一行末尾添加一个管道

问题描述

我的 awk 命令有点问题。

目标是在我的 CSV 中添加一个新列:

这是我的 csv :

email|event_date|id|type|cha|external_id|name|date
abcd@google.fr|2020-11-13 08:04:44|12|Invalid|Mail|disable|One|2020-11-13
dcab@google.fr|2020-11-13 08:04:44|13|Invalid|Mail|disable|Two|2020-11-13

我想要这个输出:

email|event_date|id|type|cha|external_id|name|date|customer_id
abcd@google.fr|2020-11-13 08:04:44|12|Invalid|Mail|disable|One|2020-11-13|20200
dcab@google.fr|2020-11-13 08:04:44|13|Invalid|Mail|disable|Two|2020-11-13|20201

但是当我做 awk 我有这个结果:

awk -v a="$(echo "${customerIdList[@]}")" 'BEGIN{FS=OFS="|"} FNR==1{$(NF+1)="customer_id"} FNR>1{split(a,b," ")} {print $0,b[NR-1]}' test.csv

email|event_date|id|type|cha|external_id|name|date|customer_id|
abcd@google.fr|2020-11-13 08:04:44|12|Invalid|Mail|disable|One|2020-11-13|20200
dcab@google.fr|2020-11-13 08:04:44|13|Invalid|Mail|disable|Two|2020-11-13|20201

其中 customerIdList = (20200 20201)

“customer_id”标题后面有一个管道,我不知道为什么:(有人可以帮我吗?

标签: awk

解决方案


您能否尝试使用显示的示例进行以下、编写和测试。

awk -v var="${customerIdList[*]}"  '
BEGIN{
  num=split(var,arr," ")
}
FNR==1{
  print $0"|customer_id"
  next
}
{
  $0=$0 (arr[FNR-1]?"|" arr[FNR-1]:"")
}
1
' Input_file

说明:为上述添加详细说明。

awk -v var="${customerIdList[*]}"  '      ##Starting awk program from here, creating var variable and passing array values to it.
BEGIN{                                    ##Starting BEGIN section of this program from here.
  num=split(var,arr," ")                  ##Splitting var into arr with space delimiter.
}
FNR==1{                                   ##Checking condition if this is first line.
  print $0"|customer_id"                  ##Then printing current line with string here.
  next                                    ##next will skip all further statements from here.
}
{
  $0=$0 (arr[FNR-1]?"|" arr[FNR-1]:"")    ##Checking condition if value of arr with current line number -1 is NOT NULL then add its value to current line with pipe else do nothing.
}
1                                         ##1 will print current line.
' Input_file                              ##Mentioning Input_file name here.

推荐阅读