Parse columns into separate arrays

梦想的初衷 提交于 2019-12-11 14:14:19

问题


I have a space-delimited file:

Pool    Library Name    Email   Subject
Finland lib1    Guru    guru@abc.com,Narendra@abc.com   Finland Media Rotation
Tucson  lib2    Albert  abc@def.com Tucson Media Rotation
Vancouver   lib3    Jeff    ghi@abc.com Vancouver Media Rotation

I want to parse the columns into arrays like:

declare -a Pool=(Finland Tucson Vancouver)
declare -a Library=(lib1 lib2 lib3)
declare -a Name=(Guru Albert Jeff)
declare -a Email=("guru@abc.com,Narendra@abc.com" abc@def.com ghi@abc.com) 

My code is:

column=1
for arrayname in Pool Library; do
     mapfile -t "$arrayname" < <(awk "NR > 1 {print \$$column}" file.txt)
     ((column++))
done

But it's failing in case of multiple items like in Email.


回答1:


Could you please try following.

awk -v s1="\"" '
FNR==1{
  for(i=1;i<=NF;i++){
    header[i]=$i
  }
  val=length(header)
  next
}
{
  match($0,/.*\.com +/)
  string=substr($0,RSTART,RLENGTH)
  num=split(string,array," ")
  for(i=1;i<=num;i++){
    values[i]=(values[i]?values[i] OFS:"")s1 array[i] s1
  }
  values[num+1]=(values[num+1]?values[num+1] OFS:"")substr($0,RSTART+RLENGTH)
  delete array
}
END{
  for(i=1;i<=val;i++){
    print "declare -a " header[i] "=(" values[i]")"
  }
}
'  Input_file

This will print the array creation commands on terminal, you could use the as per your need.



来源:https://stackoverflow.com/questions/59117448/parse-columns-into-separate-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!