删除字符串匹配bash的列 [英] remove columns with string match bash

查看:45
本文介绍了删除字符串匹配bash的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题.

我需要删除文件头中包含特定字符串的列. 分号充当列限制

I need to remove columns within a file that contain a specific string in the header. The semi-colon are acting as column limit

以下示例

file 1
ADM_THO_CVL2000,ZO,AT;BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG; 
1;2;3;
4;5;6;


file 2
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;ADM_THO_CVL2000,OZ,ES;BAG-AL,W,SE;
1;2;3;5;
4;5;6;7;

ADM_THO_CVL2000是我需要删除的特定字符串.除去字符串和后续列之后的结果如下:

ADM_THO_CVL2000 is the specific string I need to remove. The results , once string and the subsequent columns are removed, are below:

BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG; 
2;3;
5;6;

BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;BAG-AL,W,SE;
1;2;5;
4;5;7;

我在互联网上看了看.

I had a look on the internet.

awk可以完成我所期望的结果,但是我得到的结果却不是我期望的结果.我给你下面的代码:

awk can do the job that but the results I'm having, are not the one that I expect. I'm giving you the code below:

awk '
FNR==1{
    for(i=1;i<=NF;i++)
        if ($i ~ str) {
          h=(h)?h FS $i:$i
          f=(f)?f FS i:i
        }
    print h
    nf=split(f,fA,FS);next
 }
 {
 for(i=1;i<=nf;i++)
       printf("%s%c",$fA[i], (i==nf)?ORS:FS)
}' str=ADM_THO_CVL2000, 'FS=;' filename.csv

对于您的任何建议,我都很高兴.

I'm all ears for any of your suggestions.

欢呼

推荐答案

您需要在我先前的解决方案中进行一些增强.由于您无法解决该问题,因此我发布了答案:

You need some enhancements in my earlier solution. Since you could not resolve it I am posting my answer:

awk -F';' '/ADM_THO_CVL2000/{delete a; for (i=1; i<NF; i++) 
   if ($i ~ /ADM_THO_CVL2000/) a[i]; else printf "%s%s", $i, OFS; print $i; next} 
   {for (i=1; i<NF; i++) if (!(i in a)) printf "%s%s", $i, OFS; print $i }' OFS=';' file

file 1
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;
2;3;
5;6;    

file 2
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;BAG-AL,W,SE;
1;2;5;
4;5;7;

这篇关于删除字符串匹配bash的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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