在数组中找到匹配项后如何转置数据 [英] How to transpose data after when match found in array

查看:36
本文介绍了在数组中找到匹配项后如何转置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望数据是来自 xml 数据的 csv 格式

I want data to be in csv format from xml data

此问题中提供了要测试的 xml 数据在标签之间提取数据</t>

注意:xml文件中的数据可能不同,Headers也会不同

Note : The data in xml file might differ and Headers will differ as well

在这个 xml 中,它们有 3 个标题 ->姓名、年龄、课程

In this xml their are 3 headers -> NAME,AGE,COURSE

我使用下面的命令以水平格式获取数据,全部在一行中:

awk -F'(</*t>|</*t>)' 'NF>1{for(i=2;i<NF; i=i+2) printf("%s%s", $i, (i+1==NF)?ORS:OFS)}' OFS=',' demo.xml

运行上面的命令后,输出如下NAME"、Vikas"、Vijay"、Vilas"、AGE"、24"、34"、35"、COURSE"、MCA"、彩信"、MBA"

After running above command , below is the output "NAME","Vikas","Vijay","Vilas","AGE","24","34","35","COURSE","MCA","MMS","MBA"

我如何尝试实现逻辑

从用户那里获取参数,他们将有多少个标头值

Take parameter from user , how many header values will be their

在上面的 xml 中,它们是 3 个标题 ->姓名、年龄、课程

In above xml their are 3 headers -> NAME,AGE,COURSE

header_count=3

所以 3 个标题意味着将有 3 个值,例如:HEADER + 3 值姓名,维卡斯,普拉巴斯,阿琼 ->这将转置到下面

So 3 headers means will have 3 values like : HEADER + 3 values NAME,Vikas,Prabhas,Arjun -> this will be transpose to below

输出:

NAME,
Vikas,
Prabhas,
Arjun,

标题值AGE ->AGE + 3

AGE,25,34,21  will be transpose to vertical 

AGE
25
34
21

标题值相同COURSE ->COURSE + 3

COURSE,MCA,MBA,MMS  will be transpose to vertical 

COURSE
MCA
MBA
MMS

**结合 NAME、AGE、COURSE 的所有数据后的预期输出 **

**Expected Output after combing all data for NAME,AGE,COURSE **

NAME,AGE,Course
Vikas,"25",MCA
Prabhash,"34",MBA
Arjun,"21",MMS

推荐答案

使用您显示的示例,请尝试以下操作.在 GNU awk 中编写和测试,应该适用于任何 awk.

With your shown samples please try following. Written and tested in GNU awk, should work in any awk.

awk '
BEGIN{
  FS=OFS=","
}
{
  for(i=1;i<=NF;i++){
    if($i~/^"NAME"/){
      found1=1
      found2=found3=""
    }
    if($i~/^"AGE"$/){
      found1=found2=""
      found2=1
    }
    if($i~/^"COURSE"$/){
      found1=found2=""
      found3=1
    }
    if(found1){
      name[++count1]=$i
    }
    if(found2){
      age[++count2]=$i
    }
    if(found3){
      course[++count3]=$i
    }
  }
}
END{
  if(count1>=count2 && count1>=count3){ max=count1 }
  if(count2>=count1 && count2>=count3){ max=count2 }
  if(count3>=count1 && count3>=count2){ max=count3 }
  for(i=1;i<=max;i++){
      print (name[i]?name[i]:"NA",age[i]?age[i]:"NA",course[i]?course[i]:"NA")
  }
}
'  Input_file

这篇关于在数组中找到匹配项后如何转置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆