免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1621 | 回复: 3

怎样按以下规则对文本进行转换? [复制链接]

论坛徽章:
0
发表于 2009-12-28 21:28 |显示全部楼层
  1. # cat ts1
  2. mod|c1|x1
  3. mod|c2|x2
  4. mod|c3|x3
  5. mod|h1|c1|x4
  6. mod|h1|c4|x5
  7. mod|h2|c1|x6
  8. mod|h2|c3|x7
  9. mod|h2|c4|x8
  10. mod|h3|c5|x9
复制代码


有以上格式的文本,以“|”为分隔符,分3列(NF3)和4列(NF4),通过转换想得到以下文本:

  1. # cat ts2
  2. mod|c1|x1
  3. mod|c2|x2
  4. mod|c3|x3
  5. mod|h1|c1|x4
  6. mod|h1|c2|x2
  7. mod|h1|c3|x3
  8. mod|h1|c4|x5
  9. mod|h2|c1|x6
  10. mod|h2|c2|x2
  11. mod|h2|c3|x7
  12. mod|h2|c4|x8
  13. mod|h3|c1|x1
  14. mod|h3|c2|x2
  15. mod|h3|c3|x3
  16. mod|h3|c5|x9
复制代码



转换规则说明如下:({NF3}$2表示3列行第二列;{NF4}$3表示4列行第三列)
以4列行第二列h1为例--
1、当h1的{NF4}$3与{NF3}$2相同时,不需操作;
2、当h1的{NF4}$3没有{NF3}$2与之相对应时,不需操作;
3、当{NF3}$2没有h1的{NF4}$3与之相对应时,则把h1作为第二列插入该NF3列,使之变为4列。
mod|c2|x2
=> mod|h1|c2|x2

对每个4列行的第二列均需要按以上方法进行转换。

对转换规则的解释有些生涩,希望大家能看明白。期待高手指点!

论坛徽章:
0
发表于 2009-12-28 23:07 |显示全部楼层
试试:
awk -F '|' 'NF==3{a[$2]=$2"|"$3}NF==4{b[$2""$3]=$0;c[$2]=1}END{for(j in a){for(k in c){b[k""j]=b[k""j]==""?"mod|"k"|"a[j]:b[k""j]}};for(n in a){print "mod|"a[n]};for(m in b){print b[m]}}' ts1|sort

论坛徽章:
0
发表于 2009-12-29 09:06 |显示全部楼层
原帖由 sunbw001 于 2009-12-28 23:07 发表
试试:
awk -F '|' 'NF==3{a[$2]=$2"|"$3}NF==4{b[$2""$3]=$0;c[$2]=1}END{for(j in a){for(k in c){b[k""j]=b[k""j]==""?"mod|"k"|"a[j]:b[k""j]}};for(n in a){print "mod|"a[n]};for(m in b){print b[m]}}' ts1|sort


多谢楼上解答,刚测试了,好使!

但是有一个小小的问题,因为在文本中“mod”字段不是固定的词,因此,能否将mod作为$1而是“mod”这个固定的词来处理呢?

论坛徽章:
0
发表于 2009-12-29 09:15 |显示全部楼层
awk -F '|' 'NF==3{a[$2]=$2"|"$3;d[$2]=$1}NF==4{b[$2""$3]=$0;c[$2]=1}END{for(j in a){for(k in c){b[k""j]=b[k""j]==""?d[j]"|"k"|"a[j]:b[k""j]}};for(n in a){print d[n]"|"a[n]};for(m in b){print b[m]}}' ts1|sort
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP