awk如何删除除某些特定字符串之外的字段中的重复项 [英] awk how to remove duplicates in a field except for some specific strings

查看:478
本文介绍了awk如何删除除某些特定字符串之外的字段中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的csv文件的结构:

 奥斯陆公司1 Mission1 
奥斯陆公司1 Mission2
奥斯陆公司3特务专员
奥斯陆公司特殊特务
巴黎公司2任务1
巴黎公司特殊任务2
巴黎公司3特务

我想删除字段1,2,3中的所有重复项,并将其替换为空格,除了这些特殊字符串CompanyspecialMissionsPecial,以便输出为:

 奥斯陆公司1 Mission1 
Mission2
公司3特务专员
公司特殊特别
巴黎公司2
公司特别
特惠

我知道的全部o使用这一段代码删除所有的重复项:

  x [$ 1] ++ {$ 1 =} x [ $ 2] ++ {$ 2 =} x [$ 3] ++ {$ 3 =}){print $ 1,$ 2,$ 3,et .....} 
/ pre>

我不是程序员。帮助将不胜感激,将节省愚蠢奴隶的工作!非常感谢你!

解决方案

  awk'{
for (i = 1; i <= 3; i ++)
if($ i!〜/(Mission | Company)special /)
if(a [i,$ i] ++)
$ i =
printf(% - 12s%-19s%-s\\\
,$ 1,$ 2,$ 3)
}'

概念证明 HERE



编辑



更新了代码,以反映一个字段的文本可能会消除另一个字段的问题。我通过将 a [$ i] ++ 更改为 a [i,$ i] ++ 来实现此目的,以便每个字段的文本也与字段编号相关。


This is the structure of my csv file:

Oslo        Company1           Mission1
Oslo        Company1           Mission2 
Oslo        Company3           Missionspecial 
Oslo        Companyspecial     Missionspecial
Paris       Company2           Mission1
Paris       Companyspecial     Mission2 
Paris       Company3           Missionspecial

I want to delete all duplicates in fields 1,2,3 and replace them with blanks, except for those special strings "Companyspecial" "Missionspecial" so that the output is:

Oslo        Company1             Mission1
                                 Mission2
            Company3             Missionspecial
            Companyspecial       Missionspecial
Paris       Company2             
            Companyspecial       
                                 Missionspecial

All I know to do is remove all duplicates with this bit of code:

x[$1]++ {$1=""}x[$2]++ {$2=""}x[$3]++ {$3=""}){print $1,$2,$3,et.....}

I'm no programmer. Help would be greatly appreciated, will save hours of stupid slave work! Thank you much in advance!``

解决方案

awk '{
  for(i=1;i<=3;i++)
    if($i !~ /(Mission|Company)special/)
      if(a[i,$i]++)
        $i=""
  printf("%-12s%-19s%-s\n",$1,$2,$3)
}'

Proof of concept HERE

Edit

Updated code to reflect concerns about one field's text potentially removing another. I accomplish this by changing a[$i]++ to a[i,$i]++ so that each field's text is also tied to the field number.

这篇关于awk如何删除除某些特定字符串之外的字段中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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