Awk adding a pipe at the end of the first line

Viewed 98

I have a little problem with my awk command.

The objective is to add a new column to my CSV :

  • The header must be "customer_id"
  • The next rows must be a customer_id from an array

Here is my 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

I would like to have this output :

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

But when I'm doing the awk I have this result :

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

Where customerIdList = (20200 20201)

There is a pipe just after the "customer_id" header and I don't know why :( Can someone help me ?

2 Answers

Could you please try following, written and tested with shown samples.

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

Explanation: Adding detailed explanation for above.

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.
awk -v IdList="${customerIdList[*]}" 'BEGIN { split(IdList,ListId," ") } NR > 1 { $0=$0"|"ListId[NR-1]}1' file

An array will need to be created within awk and so pass the array as a space separated string and then use awk's split function to create the array IdList. The ignoring the headers (NR>1), set the line equal to the line plus the index of ListId array NR-1.

Related